From 95a9d46a87a14ea4e29fa3ead51f4a0fad5ad24c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 23 May 2019 15:48:03 -0700 Subject: [PATCH] Migrate Hamcrest assertions to AssertJ Migrate all existing `assertThat(..., Matcher)` assertions to AssertJ and add checkstyle rules to ensure they don't return. See gh-23022 --- .../AbstractAspectJAdvisorFactoryTests.java | 7 +- .../aop/framework/ProxyFactoryTests.java | 10 +- ...elegatingIntroductionInterceptorTests.java | 5 +- .../AnnotationAsyncExecutionAspectTests.java | 12 +- .../beans/AbstractPropertyAccessorTests.java | 35 +- .../beans/BeanWrapperAutoGrowingTests.java | 35 +- .../CachedIntrospectionResultsTests.java | 16 +- .../beans/ExtendedBeanInfoFactoryTests.java | 17 +- .../beans/ExtendedBeanInfoTests.java | 403 +++++----- .../beans/MutablePropertyValuesTests.java | 16 +- .../beans/PropertyMatchesTests.java | 67 +- .../beans/SimplePropertyDescriptorTests.java | 83 +- .../DefaultListableBeanFactoryTests.java | 78 +- .../beans/factory/FactoryBeanLookupTests.java | 7 +- .../PropertyPlaceholderConfigurerTests.java | 33 +- .../YamlPropertiesFactoryBeanTests.java | 81 +- .../beans/factory/support/Spr8954Tests.java | 37 +- .../factory/xml/DuplicateBeanIdTests.java | 6 +- ...edBeansElementAttributeRecursionTests.java | 71 +- .../factory/xml/NestedBeansElementTests.java | 8 +- .../xml/ProfileXmlBeanDefinitionTests.java | 116 ++- .../CandidateComponentsIndexerTests.java | 32 +- .../context/index/processor/Metadata.java | 86 +- .../processor/PropertiesMarshallerTests.java | 12 +- ...ransactionSupportingCacheManagerTests.java | 19 +- .../SpringValidatorAdapterTests.java | 60 +- .../ValidatorFactoryTests.java | 5 +- .../aop/framework/CglibProxyTests.java | 5 +- .../aop/framework/ObjenesisProxyTests.java | 8 +- .../aop/framework/ProxyFactoryBeanTests.java | 11 +- .../factory/xml/XmlBeanFactoryTests.java | 4 +- .../cache/AbstractCacheTests.java | 5 +- .../AnnotationCacheOperationSourceTests.java | 40 +- .../config/AbstractCacheAnnotationTests.java | 8 +- .../interceptor/ExpressionEvaluatorTests.java | 12 +- .../interceptor/SimpleKeyGeneratorTests.java | 69 +- ...notationConfigApplicationContextTests.java | 27 +- .../annotation/BeanMethodMetadataTests.java | 11 +- .../BeanMethodPolymorphismTests.java | 17 +- ...anningCandidateComponentProviderTests.java | 36 +- ...mponentScanAnnotationIntegrationTests.java | 88 +- ...ComponentScanAnnotationRecursionTests.java | 8 +- .../annotation/ComponentScanParserTests.java | 9 +- .../ConfigurationClassAndBFPPTests.java | 13 +- ...nClassPostConstructAndAutowiringTests.java | 10 +- .../ConfigurationClassWithConditionTests.java | 5 +- .../DestroyMethodInferenceTests.java | 62 +- .../EnableAspectJAutoProxyTests.java | 9 +- .../context/annotation/ImportAwareTests.java | 22 +- .../ImportBeanDefinitionRegistrarTests.java | 13 +- .../annotation/ImportSelectorTests.java | 82 +- .../NestedConfigurationClassTests.java | 15 +- ...PrimitiveBeanLookupAndAutowiringTests.java | 20 +- .../PropertySourceAnnotationTests.java | 66 +- .../ReflectionUtilsIntegrationTests.java | 5 +- .../RoleAndDescriptionAnnotationTests.java | 34 +- .../context/annotation/Spr12278Tests.java | 7 +- .../context/annotation/Spr6602Tests.java | 13 +- .../context/annotation/Spr8954Tests.java | 30 +- .../AutowiredConfigurationTests.java | 29 +- .../BeanMethodQualificationTests.java | 25 +- .../ConfigurationBeanNameTests.java | 28 +- ...figurationClassAspectIntegrationTests.java | 8 +- ...assWithPlaceholderConfigurerBeanTests.java | 15 +- .../ConfigurationMetaAnnotationTests.java | 9 +- .../ImportAnnotationDetectionTests.java | 26 +- .../configuration/ImportResourceTests.java | 5 +- .../annotation/configuration/ImportTests.java | 16 +- ...tedConfigurationClassEnhancementTests.java | 8 +- ...kagePrivateBeanMethodInheritanceTests.java | 11 +- .../configuration/Spr10744Tests.java | 21 +- .../configuration/Spr7167Tests.java | 9 +- .../configuration/spr9031/Spr9031Tests.java | 9 +- .../annotation/spr10546/Spr10546Tests.java | 8 +- .../annotation/spr8761/Spr8761Tests.java | 6 +- .../AnnotationDrivenEventListenerTests.java | 7 +- .../EnvironmentAccessorIntegrationTests.java | 5 +- .../CandidateComponentsIndexLoaderTests.java | 29 +- .../index/CandidateComponentsIndexTests.java | 27 +- .../ConversionServiceFactoryBeanTests.java | 7 +- .../support/EnvironmentIntegrationTests.java | 10 +- ...onmentSecurityManagerIntegrationTests.java | 8 +- .../GenericXmlApplicationContextTests.java | 12 +- ...ertySourcesPlaceholderConfigurerTests.java | 44 +- ...erializableBeanFactoryMemoryLeakTests.java | 9 +- .../format/datetime/DateFormatterTests.java | 65 +- .../format/datetime/DateFormattingTests.java | 5 +- .../DateTimeFormatterFactoryBeanTests.java | 19 +- .../joda/DateTimeFormatterFactoryTests.java | 20 +- .../joda/JodaTimeFormattingTests.java | 5 +- .../DateTimeFormatterFactoryBeanTests.java | 19 +- .../DateTimeFormatterFactoryTests.java | 20 +- .../jndi/JndiLocatorDelegateTests.java | 7 +- .../jndi/JndiPropertySourceTests.java | 14 +- ...otationAsyncExecutionInterceptorTests.java | 14 +- .../annotation/EnableAsyncTests.java | 32 +- .../annotation/EnableSchedulingTests.java | 29 +- ...heduledTasksBeanDefinitionParserTests.java | 5 +- .../DefaultMessageCodesResolverTests.java | 51 +- .../SpringValidatorAdapterTests.java | 56 +- .../beanvalidation/ValidatorFactoryTests.java | 7 +- spring-core/spring-core.gradle | 1 + .../core/CollectionFactoryTests.java | 72 +- .../core/GenericTypeResolverTests.java | 25 +- .../core/ResolvableTypeTests.java | 761 +++++++++--------- .../core/SerializableTypeWrapperTests.java | 23 +- ...dReflectionParameterNameDiscoverTests.java | 6 +- .../annotation/AnnotationAttributesTests.java | 40 +- .../AnnotationAwareOrderComparatorTests.java | 6 +- .../core/annotation/AnnotationUtilsTests.java | 45 +- .../core/convert/TypeDescriptorTests.java | 18 +- .../converter/ConvertingComparatorTests.java | 23 +- .../DefaultConversionServiceTests.java | 11 +- .../support/ByteBufferConverterTests.java | 33 +- .../GenericConversionServiceTests.java | 5 +- .../support/MapToMapConverterTests.java | 15 +- .../core/env/CustomEnvironmentTests.java | 36 +- .../JOptCommandLinePropertySourceTests.java | 59 +- .../core/env/MutablePropertySourcesTests.java | 127 ++- .../core/env/PropertySourceTests.java | 49 +- .../PropertySourcesPropertyResolverTests.java | 126 ++- .../env/SimpleCommandLineParserTests.java | 38 +- .../SimpleCommandLinePropertySourceTests.java | 68 +- .../core/env/StandardEnvironmentTests.java | 175 ++-- .../SystemEnvironmentPropertySourceTests.java | 128 +-- .../core/io/PathResourceTests.java | 64 +- .../core/io/ResourceTests.java | 8 +- .../support/ResourcePropertySourceTests.java | 17 +- .../task/SimpleAsyncTaskExecutorTests.java | 5 +- ...AbstractClassMetadataMemberClassTests.java | 12 +- .../core/type/AnnotationMetadataTests.java | 192 +++-- .../type/CachingMetadataReaderLeakTests.java | 8 +- .../springframework/tests/AssumeTests.java | 17 +- .../springframework/tests/MockitoUtils.java | 13 +- .../springframework/tests/TestGroupTests.java | 22 +- .../org/springframework/tests/XmlContent.java | 54 ++ .../tests/XmlContentAssert.java | 65 ++ .../util/ConcurrentReferenceHashMapTests.java | 264 +++--- .../util/ObjectUtilsTests.java | 25 +- .../util/ReflectionUtilsTests.java | 18 +- .../util/StreamUtilsTests.java | 15 +- .../comparator/BooleanComparatorTests.java | 20 +- .../comparator/InstanceComparatorTests.java | 36 +- .../comparator/InvertibleComparatorTests.java | 20 +- .../SettableListenableFutureTests.java | 19 +- .../util/xml/AbstractStaxHandlerTestCase.java | 14 +- .../util/xml/DomContentHandlerTests.java | 11 +- .../xml/ListBasedXMLEventReaderTests.java | 7 +- .../util/xml/SimpleNamespaceContextTests.java | 129 ++- .../util/xml/StaxResultTests.java | 9 +- .../util/xml/StaxSourceTests.java | 13 +- .../util/xml/XMLEventStreamReaderTests.java | 7 +- .../util/xml/XMLEventStreamWriterTests.java | 7 +- .../expression/spel/EvaluationTests.java | 6 +- .../expression/spel/MapAccessTests.java | 5 +- .../expression/spel/SpelReproTests.java | 13 +- .../config/JdbcNamespaceIntegrationTests.java | 11 +- .../jdbc/core/JdbcTemplateTests.java | 8 +- .../BeanPropertySqlParameterSourceTests.java | 36 +- .../jdbc/core/support/SqlLobValueTests.java | 5 +- .../datasource/DelegatingDataSourceTests.java | 20 +- .../AbstractDatabaseInitializationTests.java | 11 +- .../init/AbstractDatabasePopulatorTests.java | 43 +- .../init/H2DatabasePopulatorTests.java | 7 +- .../jdbc/object/SqlQueryTests.java | 18 +- .../support/SQLErrorCodesFactoryTests.java | 5 +- .../SQLExceptionCustomTranslatorTests.java | 7 +- spring-messaging/spring-messaging.gradle | 1 + .../MappingJackson2MessageConverterTests.java | 19 +- .../MarshallingMessageConverterTests.java | 6 +- .../invocation/MethodMessageHandlerTests.java | 5 +- .../reactive/MethodMessageHandlerTests.java | 7 +- .../SimpAttributesContextHolderTests.java | 31 +- .../messaging/simp/SimpAttributesTests.java | 21 +- .../messaging/simp/SimpSessionScopeTests.java | 18 +- ...mpAnnotationMethodMessageHandlerTests.java | 5 +- .../MessageBrokerConfigurationTests.java | 35 +- .../simp/stomp/DefaultStompSessionTests.java | 7 +- .../ReactorNettyTcpStompClientTests.java | 7 +- .../simp/stomp/StompHeaderAccessorTests.java | 5 +- .../user/MultiServerUserRegistryTests.java | 7 +- .../messaging/support/ErrorMessageTests.java | 11 +- .../ExecutorSubscribableChannelTests.java | 13 +- .../support/MessageHeaderAccessorTests.java | 5 +- .../jpa/SharedEntityManagerCreatorTests.java | 6 +- .../DefaultPersistenceUnitManagerTests.java | 9 +- spring-oxm/spring-oxm.gradle | 1 + .../oxm/AbstractMarshallerTests.java | 26 +- .../oxm/jaxb/Jaxb2MarshallerTests.java | 11 +- .../oxm/jibx/JibxMarshallerTests.java | 6 +- .../oxm/xstream/XStreamMarshallerTests.java | 34 +- .../mock/web/MockFilterChainTests.java | 7 +- .../ContextHierarchyDirtiesContextTests.java | 16 +- .../context/TestContextConcurrencyTests.java | 5 +- .../TestPropertySourceInterfaceTests.java | 8 +- ...inedPropertiesTestPropertySourceTests.java | 19 +- ...TestExecutionListenerIntegrationTests.java | 10 +- ...tPublishingTestExecutionListenerTests.java | 12 +- .../jupiter/DisabledIfConditionTests.java | 52 +- ...ltipleWebRequestsSpringExtensionTests.java | 2 +- .../jupiter/web/WebSpringExtensionTests.java | 2 +- .../spr6128/AutowiredQualifierTests.java | 7 +- ...ntextLoaderUtilsContextHierarchyTests.java | 123 ++- .../test/jdbc/JdbcTestUtilsTests.java | 9 +- .../test/util/AopTestUtilsTests.java | 7 +- .../match/ContentRequestMatchersTests.java | 1 + .../match/JsonPathRequestMatchersTests.java | 3 +- .../match/MockRestRequestMatchersTests.java | 22 +- .../reactive/server/HeaderAssertionTests.java | 2 +- .../reactive/server/MockServerSpecTests.java | 7 +- .../server/samples/JsonContentTests.java | 2 + .../server/samples/ResponseEntityTests.java | 11 +- .../server/samples/XmlContentTests.java | 2 + .../test/web/servlet/MockMvcReuseTests.java | 2 +- .../DelegatingWebConnectionTests.java | 16 +- .../htmlunit/HtmlUnitRequestBuilderTests.java | 262 +++--- .../MockMvcConnectionBuilderSupportTests.java | 13 +- .../MockMvcWebClientBuilderTests.java | 23 +- .../htmlunit/MockMvcWebConnectionTests.java | 9 +- .../htmlunit/MockWebResponseBuilderTests.java | 49 +- .../MockMvcHtmlUnitDriverBuilderTests.java | 13 +- .../WebConnectionHtmlUnitDriverTests.java | 8 +- .../result/ModelResultMatchersTests.java | 2 + ...stAttributesRequestContextHolderTests.java | 21 +- .../spr/RequestContextHolderTests.java | 27 +- .../resultmatchers/HeaderAssertionTests.java | 10 +- ...ConditionalDelegatingFilterProxyTests.java | 27 +- .../TxNamespaceHandlerEventTests.java | 6 +- .../EnableTransactionManagementTests.java | 27 +- .../interceptor/RollbackRuleTests.java | 5 +- spring-web/spring-web.gradle | 1 + .../http/CacheControlTests.java | 28 +- .../http/HttpHeadersTests.java | 41 +- .../http/ResponseCookieTests.java | 17 +- .../http/ResponseEntityTests.java | 9 +- .../client/AbstractMockWebServerTestCase.java | 21 +- .../client/SimpleClientHttpResponseTests.java | 19 +- .../InterceptingHttpAccessorTests.java | 10 +- .../codec/ResourceHttpMessageWriterTests.java | 29 +- .../http/codec/xml/Jaxb2XmlEncoderTests.java | 6 +- .../FormHttpMessageConverterTests.java | 13 +- .../ResourceHttpMessageConverterTests.java | 10 +- ...sourceRegionHttpMessageConverterTests.java | 64 +- .../AtomFeedHttpMessageConverterTests.java | 8 +- .../RssChannelHttpMessageConverterTests.java | 11 +- .../Jackson2ObjectMapperBuilderTests.java | 26 +- .../Jackson2ObjectMapperFactoryBeanTests.java | 11 +- ...pingJackson2HttpMessageConverterTests.java | 20 +- ...2RootElementHttpMessageConverterTests.java | 16 +- ...gJackson2XmlHttpMessageConverterTests.java | 10 +- .../xml/SourceHttpMessageConverterTests.java | 20 +- .../reactive/AsyncIntegrationTests.java | 6 +- .../reactive/CookieIntegrationTests.java | 18 +- .../support/WebRequestDataBinderTests.java | 15 +- .../client/AbstractMockWebServerTestCase.java | 9 +- .../client/HttpStatusCodeExceptionTests.java | 5 +- .../web/client/RestTemplateTests.java | 7 +- ...ationConfigWebApplicationContextTests.java | 5 +- .../StandardServletEnvironmentTests.java | 17 +- .../web/cors/DefaultCorsProcessorTests.java | 83 +- .../reactive/DefaultCorsProcessorTests.java | 83 +- .../reactive/HiddenHttpMethodFilterTests.java | 5 +- ...ndardMultipartHttpServletRequestTests.java | 7 +- .../web/util/UriComponentsBuilderTests.java | 75 +- .../web/util/UriComponentsTests.java | 23 +- .../web/util/pattern/PathPatternTests.java | 4 +- .../reactive/DispatcherHandlerErrorTests.java | 19 +- .../config/ResourceHandlerRegistryTests.java | 71 +- .../reactive/function/BodyInsertersTests.java | 11 +- .../client/WebClientIntegrationTests.java | 7 +- .../AppCacheManifestTransformerTests.java | 22 +- .../resource/ResourceUrlProviderTests.java | 42 +- .../resource/ResourceWebHandlerTests.java | 15 +- .../VersionResourceResolverTests.java | 27 +- .../method/HandlerMethodMappingTests.java | 11 +- .../method/InvocableHandlerMethodTests.java | 5 +- ...RequestMappingInfoHandlerMappingTests.java | 7 +- .../GlobalCorsConfigIntegrationTests.java | 17 +- .../socket/WebSocketIntegrationTests.java | 5 +- .../HandshakeWebSocketServiceTests.java | 13 +- spring-webmvc/spring-webmvc.gradle | 1 + .../web/context/ContextLoaderTests.java | 30 +- .../XmlWebApplicationContextTests.java | 10 +- .../web/servlet/DispatcherServletTests.java | 14 +- ...tationDrivenBeanDefinitionParserTests.java | 10 +- .../web/servlet/config/MvcNamespaceTests.java | 75 +- .../ResourceHandlerRegistryTests.java | 72 +- .../servlet/handler/HandlerMappingTests.java | 8 +- .../mvc/WebContentInterceptorTests.java | 36 +- .../HttpEntityMethodProcessorMockTests.java | 5 +- .../MvcUriComponentsBuilderTests.java | 76 +- ...MappingHandlerAdapterIntegrationTests.java | 5 +- .../AppCacheManifestTransformerTests.java | 22 +- .../ResourceHttpRequestHandlerTests.java | 5 +- .../resource/ResourceUrlProviderTests.java | 5 +- .../VersionResourceResolverTests.java | 21 +- .../web/servlet/tags/UrlTagTests.java | 5 +- .../view/ResourceBundleViewResolverTests.java | 9 +- .../servlet/view/feed/AtomFeedViewTests.java | 9 +- .../servlet/view/feed/RssFeedViewTests.java | 6 +- .../freemarker/FreeMarkerConfigurerTests.java | 5 +- .../groovy/GroovyMarkupConfigurerTests.java | 26 +- .../view/groovy/GroovyMarkupViewTests.java | 5 +- .../json/MappingJackson2JsonViewTests.java | 8 +- .../web/socket/TextMessageTests.java | 12 +- .../web/socket/WebSocketExtensionTests.java | 10 +- .../ConvertingEncoderDecoderSupportTests.java | 31 +- .../HandlersBeanDefinitionParserTests.java | 56 +- ...essageBrokerBeanDefinitionParserTests.java | 61 +- .../handler/WebSocketHttpHeadersTests.java | 6 +- .../StompSubProtocolHandlerTests.java | 5 +- .../WebSocketStompClientIntegrationTests.java | 5 +- .../client/ClientSockJsSessionTests.java | 39 +- .../sockjs/client/SockJsUrlInfoTests.java | 8 +- src/checkstyle/checkstyle-suppressions.xml | 6 + src/checkstyle/checkstyle.xml | 7 + .../ComponentBeanDefinitionParserTests.java | 18 +- .../EnableCachingIntegrationTests.java | 5 +- .../EnvironmentSystemIntegrationTests.java | 151 ++-- ...ansactionalAnnotationIntegrationTests.java | 20 +- ...TransactionManagementIntegrationTests.java | 23 +- .../ProxyAnnotationDiscoveryTests.java | 16 +- 322 files changed, 4358 insertions(+), 4814 deletions(-) create mode 100644 spring-core/src/test/java/org/springframework/tests/XmlContent.java create mode 100644 spring-core/src/test/java/org/springframework/tests/XmlContentAssert.java 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 6c083cb794..97f9a9e558 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 @@ -58,11 +58,10 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; @@ -384,7 +383,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { CannotBeUnlocked.class ), CannotBeUnlocked.class); - assertThat(proxy, instanceOf(Lockable.class)); + assertThat(proxy).isInstanceOf(Lockable.class); Lockable lockable = proxy; assertTrue("Already locked", lockable.locked()); lockable.lock(); @@ -429,7 +428,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean"))); Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class); - assertThat(modifiable, instanceOf(Modifiable.class)); + assertThat(modifiable).isInstanceOf(Modifiable.class); Lockable lockable = (Lockable) modifiable; assertFalse(lockable.locked()); 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 e671f0ad69..d71c958dc5 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 @@ -42,9 +42,8 @@ import org.springframework.tests.sample.beans.IOther; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -187,7 +186,7 @@ public class ProxyFactoryTests { // This call should be ignored without error pf.addInterface(TimeStamped.class); // All cool - assertThat(pf.getProxy(), instanceOf(TimeStamped.class)); + assertThat(pf.getProxy()).isInstanceOf(TimeStamped.class); } @Test @@ -204,8 +203,7 @@ public class ProxyFactoryTests { //System.out.println("Proxied interfaces are " + StringUtils.arrayToDelimitedString(factory.getProxiedInterfaces(), ",")); assertEquals("Found correct number of interfaces", 5, factory.getProxiedInterfaces().length); ITestBean tb = (ITestBean) factory.getProxy(); - assertThat("Picked up secondary interface", tb, instanceOf(IOther.class)); - + assertThat(tb).as("Picked up secondary interface").isInstanceOf(IOther.class); raw.setAge(25); assertTrue(tb.getAge() == raw.getAge()); @@ -238,7 +236,7 @@ public class ProxyFactoryTests { NopInterceptor diUnused = new NopInterceptor(); ProxyFactory factory = new ProxyFactory(new TestBean()); factory.addAdvice(0, di); - assertThat(factory.getProxy(), instanceOf(ITestBean.class)); + assertThat(factory.getProxy()).isInstanceOf(ITestBean.class); assertTrue(factory.adviceIncluded(di)); assertTrue(!factory.adviceIncluded(diUnused)); assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1); 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 e61808e39f..2fbd09a418 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 @@ -34,9 +34,8 @@ import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -162,7 +161,7 @@ public class DelegatingIntroductionInterceptorTests { //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); TimeStamped ts = (TimeStamped) pf.getProxy(); - assertThat(ts, instanceOf(TimeStamped.class)); + assertThat(ts).isInstanceOf(TimeStamped.class); // Shouldn't proxy framework interfaces assertTrue(!(ts instanceof MethodInterceptor)); assertTrue(!(ts instanceof IntroductionInterceptor)); diff --git a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java index d90e50a853..2ad5f33fac 100644 --- a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java @@ -38,9 +38,7 @@ import org.springframework.tests.TestGroup; import org.springframework.util.ReflectionUtils; import org.springframework.util.concurrent.ListenableFuture; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -140,14 +138,14 @@ public class AnnotationAsyncExecutionAspectTests { ClassWithQualifiedAsyncMethods obj = new ClassWithQualifiedAsyncMethods(); Future defaultThread = obj.defaultWork(); - assertThat(defaultThread.get(), not(Thread.currentThread())); - assertThat(defaultThread.get().getName(), not(startsWith("e1-"))); + assertThat(defaultThread.get()).isNotEqualTo(Thread.currentThread()); + assertThat(defaultThread.get().getName()).doesNotStartWith("e1-"); ListenableFuture e1Thread = obj.e1Work(); - assertThat(e1Thread.get().getName(), startsWith("e1-")); + assertThat(e1Thread.get().getName()).startsWith("e1-"); CompletableFuture e1OtherThread = obj.e1OtherWork(); - assertThat(e1OtherThread.get().getName(), startsWith("e1-")); + assertThat(e1OtherThread.get().getName()).startsWith("e1-"); } @Test 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 4df802af31..fd706fd1fa 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java @@ -61,11 +61,6 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -98,7 +93,7 @@ public abstract class AbstractPropertyAccessorTests { public void isReadableProperty() { AbstractPropertyAccessor accessor = createAccessor(new Simple("John", 2)); - assertThat(accessor.isReadableProperty("name"), is(true)); + assertThat(accessor.isReadableProperty("name")).isTrue(); } @Test @@ -130,7 +125,7 @@ public abstract class AbstractPropertyAccessorTests { public void isWritableProperty() { AbstractPropertyAccessor accessor = createAccessor(new Simple("John", 2)); - assertThat(accessor.isWritableProperty("name"), is(true)); + assertThat(accessor.isWritableProperty("name")).isTrue(); } @Test @@ -198,21 +193,21 @@ public abstract class AbstractPropertyAccessorTests { public void getSimpleProperty() { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyValue("name"), is("John")); + assertThat(accessor.getPropertyValue("name")).isEqualTo("John"); } @Test public void getNestedProperty() { Person target = createPerson("John", "London", "UK"); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyValue("address.city"), is("London")); + assertThat(accessor.getPropertyValue("address.city")).isEqualTo("London"); } @Test public void getNestedDeepProperty() { Person target = createPerson("John", "London", "UK"); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyValue("address.country.name"), is("UK")); + assertThat(accessor.getPropertyValue("address.country.name")).isEqualTo("UK"); } @Test @@ -291,8 +286,8 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("name", "SomeValue"); - assertThat(target.name, is("SomeValue")); - assertThat(target.getName(), is("SomeValue")); + assertThat(target.name).isEqualTo("SomeValue"); + assertThat(target.getName()).isEqualTo("SomeValue"); } @Test @@ -301,7 +296,7 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("address.city", "London"); - assertThat(target.address.city, is("London")); + assertThat(target.address.city).isEqualTo("London"); } @Test @@ -364,7 +359,7 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("address.country.name", "UK"); - assertThat(target.address.country.name, is("UK")); + assertThat(target.address.country.name).isEqualTo("UK"); } @Test @@ -413,7 +408,7 @@ public abstract class AbstractPropertyAccessorTests { accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("address.country.name", "UK"); - assertThat(target.address.country.name, is("UK")); + assertThat(target.address.country.name).isEqualTo("UK"); } @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes") @@ -1108,11 +1103,11 @@ public abstract class AbstractPropertyAccessorTests { Object[] array = new Object[] {"1", "2"}; accessor.setPropertyValue("object", array); - assertThat(target.getObject(), equalTo((Object) array)); + assertThat(target.getObject()).isEqualTo(array); array = new Object[] {"1"}; accessor.setPropertyValue("object", array); - assertThat(target.getObject(), equalTo((Object) array)); + assertThat(target.getObject()).isEqualTo(array); } @@ -1636,7 +1631,7 @@ public abstract class AbstractPropertyAccessorTests { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyType("foo"), is(nullValue())); + assertThat(accessor.getPropertyType("foo")).isNull(); } @Test @@ -1644,7 +1639,7 @@ public abstract class AbstractPropertyAccessorTests { Person target = createPerson("John", "Paris", "FR"); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyTypeDescriptor("address.city"), is(notNullValue())); + assertThat(accessor.getPropertyTypeDescriptor("address.city")).isNotNull(); } @Test @@ -1652,7 +1647,7 @@ public abstract class AbstractPropertyAccessorTests { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyTypeDescriptor("foo"), is(nullValue())); + assertThat(accessor.getPropertyTypeDescriptor("foo")).isNull(); } @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 28971c35ae..57eb876037 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java @@ -22,9 +22,8 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -67,7 +66,7 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowArray() { assertNotNull(wrapper.getPropertyValue("array[0]")); assertEquals(1, bean.getArray().length); - assertThat(bean.getArray()[0], instanceOf(Bean.class)); + assertThat(bean.getArray()[0]).isInstanceOf(Bean.class); } @Test @@ -80,11 +79,11 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowArrayBySeveralElements() { assertNotNull(wrapper.getPropertyValue("array[4]")); assertEquals(5, bean.getArray().length); - assertThat(bean.getArray()[0], instanceOf(Bean.class)); - assertThat(bean.getArray()[1], instanceOf(Bean.class)); - assertThat(bean.getArray()[2], instanceOf(Bean.class)); - assertThat(bean.getArray()[3], instanceOf(Bean.class)); - assertThat(bean.getArray()[4], instanceOf(Bean.class)); + assertThat(bean.getArray()[0]).isInstanceOf(Bean.class); + assertThat(bean.getArray()[1]).isInstanceOf(Bean.class); + assertThat(bean.getArray()[2]).isInstanceOf(Bean.class); + assertThat(bean.getArray()[3]).isInstanceOf(Bean.class); + assertThat(bean.getArray()[4]).isInstanceOf(Bean.class); assertNotNull(wrapper.getPropertyValue("array[0]")); assertNotNull(wrapper.getPropertyValue("array[1]")); assertNotNull(wrapper.getPropertyValue("array[2]")); @@ -95,14 +94,14 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowMultiDimensionalArray() { assertNotNull(wrapper.getPropertyValue("multiArray[0][0]")); assertEquals(1, bean.getMultiArray()[0].length); - assertThat(bean.getMultiArray()[0][0], instanceOf(Bean.class)); + assertThat(bean.getMultiArray()[0][0]).isInstanceOf(Bean.class); } @Test public void getPropertyValueAutoGrowList() { assertNotNull(wrapper.getPropertyValue("list[0]")); assertEquals(1, bean.getList().size()); - assertThat(bean.getList().get(0), instanceOf(Bean.class)); + assertThat(bean.getList().get(0)).isInstanceOf(Bean.class); } @Test @@ -115,11 +114,11 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowListBySeveralElements() { assertNotNull(wrapper.getPropertyValue("list[4]")); assertEquals(5, bean.getList().size()); - assertThat(bean.getList().get(0), instanceOf(Bean.class)); - assertThat(bean.getList().get(1), instanceOf(Bean.class)); - assertThat(bean.getList().get(2), instanceOf(Bean.class)); - assertThat(bean.getList().get(3), instanceOf(Bean.class)); - assertThat(bean.getList().get(4), instanceOf(Bean.class)); + assertThat(bean.getList().get(0)).isInstanceOf(Bean.class); + assertThat(bean.getList().get(1)).isInstanceOf(Bean.class); + assertThat(bean.getList().get(2)).isInstanceOf(Bean.class); + assertThat(bean.getList().get(3)).isInstanceOf(Bean.class); + assertThat(bean.getList().get(4)).isInstanceOf(Bean.class); assertNotNull(wrapper.getPropertyValue("list[0]")); assertNotNull(wrapper.getPropertyValue("list[1]")); assertNotNull(wrapper.getPropertyValue("list[2]")); @@ -138,7 +137,7 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowMultiDimensionalList() { assertNotNull(wrapper.getPropertyValue("multiList[0][0]")); assertEquals(1, bean.getMultiList().get(0).size()); - assertThat(bean.getMultiList().get(0).get(0), instanceOf(Bean.class)); + assertThat(bean.getMultiList().get(0).get(0)).isInstanceOf(Bean.class); } @Test @@ -150,13 +149,13 @@ public class BeanWrapperAutoGrowingTests { @Test public void setPropertyValueAutoGrowMap() { wrapper.setPropertyValue("map[A]", new Bean()); - assertThat(bean.getMap().get("A"), instanceOf(Bean.class)); + assertThat(bean.getMap().get("A")).isInstanceOf(Bean.class); } @Test public void setNestedPropertyValueAutoGrowMap() { wrapper.setPropertyValue("map[A].nested", new Bean()); - assertThat(bean.getMap().get("A").getNested(), instanceOf(Bean.class)); + assertThat(bean.getMap().get("A").getNested()).isInstanceOf(Bean.class); } diff --git a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java index 86579505fc..cf96563d3b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java @@ -25,9 +25,7 @@ import org.junit.Test; import org.springframework.core.OverridingClassLoader; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -87,13 +85,11 @@ public class CachedIntrospectionResultsTests { } // resulting in a property descriptor including the non-standard setFoo method - assertThat(pd, notNullValue()); - assertThat(pd.getReadMethod(), equalTo(C.class.getMethod("getFoo"))); - assertThat( - "No write method found for non-void returning 'setFoo' method. " + - "Check to see if CachedIntrospectionResults is delegating to " + - "ExtendedBeanInfo as expected", - pd.getWriteMethod(), equalTo(C.class.getMethod("setFoo", String.class))); + assertThat(pd).isNotNull(); + assertThat(pd.getReadMethod()).isEqualTo(C.class.getMethod("getFoo")); + // No write method found for non-void returning 'setFoo' method. + // Check to see if CachedIntrospectionResults is delegating to ExtendedBeanInfo as expected + assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class)); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoFactoryTests.java index 0a8ef9ad62..6ed39ca522 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoFactoryTests.java @@ -20,9 +20,8 @@ import java.beans.IntrospectionException; import org.junit.Test; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link ExtendedBeanInfoTests}. @@ -39,7 +38,7 @@ public class ExtendedBeanInfoFactoryTests { class C { public void setFoo(String s) { } } - assertThat(factory.getBeanInfo(C.class), nullValue()); + assertThat(factory.getBeanInfo(C.class)).isNull(); } @Test @@ -48,7 +47,7 @@ public class ExtendedBeanInfoFactoryTests { class C { public C setFoo(String s) { return this; } } - assertThat(factory.getBeanInfo(C.class), notNullValue()); + assertThat(factory.getBeanInfo(C.class)).isNotNull(); } @Test @@ -57,7 +56,7 @@ public class ExtendedBeanInfoFactoryTests { class C { public C setFoo(int i, String s) { return this; } } - assertThat(factory.getBeanInfo(C.class), notNullValue()); + assertThat(factory.getBeanInfo(C.class)).isNotNull(); } @Test @@ -66,7 +65,7 @@ public class ExtendedBeanInfoFactoryTests { class C { void setBar(String s) { } } - assertThat(factory.getBeanInfo(C.class), nullValue()); + assertThat(factory.getBeanInfo(C.class)).isNull(); } @Test @@ -75,7 +74,7 @@ public class ExtendedBeanInfoFactoryTests { class C { C setBar() { return this; } } - assertThat(factory.getBeanInfo(C.class), nullValue()); + assertThat(factory.getBeanInfo(C.class)).isNull(); } @Test @@ -84,7 +83,7 @@ public class ExtendedBeanInfoFactoryTests { class C { C set(String s) { return this; } } - assertThat(factory.getBeanInfo(C.class), nullValue()); + assertThat(factory.getBeanInfo(C.class)).isNull(); } } 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 0aae952562..8b1142d23a 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -27,11 +27,7 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.lessThan; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -51,11 +47,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse(); } @Test @@ -67,11 +63,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test @@ -84,11 +80,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test @@ -100,11 +96,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test @@ -116,16 +112,16 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test @@ -137,15 +133,15 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foo")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test @@ -158,20 +154,20 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { if (pd.getName().equals("foo")) { - assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); + assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class)); return; } } @@ -193,11 +189,11 @@ public class ExtendedBeanInfoTests { } { // always passes ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Parent.class)); - assertThat(hasReadMethodForProperty(bi, "property1"), is(true)); + assertThat(hasReadMethodForProperty(bi, "property1")).isTrue(); } { // failed prior to fix for SPR-9414 ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Child.class)); - assertThat(hasReadMethodForProperty(bi, "property1"), is(true)); + assertThat(hasReadMethodForProperty(bi, "property1")).isTrue(); } } @@ -211,11 +207,11 @@ public class ExtendedBeanInfoTests { } { // always passes BeanInfo info = Introspector.getBeanInfo(Bean.class); - assertThat(info.getPropertyDescriptors().length, equalTo(2)); + assertThat(info.getPropertyDescriptors().length).isEqualTo(2); } { // failed prior to fix for SPR-9453 BeanInfo info = new ExtendedBeanInfo(Introspector.getBeanInfo(Bean.class)); - assertThat(info.getPropertyDescriptors().length, equalTo(2)); + assertThat(info.getPropertyDescriptors().length).isEqualTo(2); } } @@ -230,16 +226,16 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test @@ -268,30 +264,30 @@ public class ExtendedBeanInfoTests { .setFoo("blue") .setBar(42); - assertThat(c.getFoo(), is("blue")); - assertThat(c.getBar(), is(42)); + assertThat(c.getFoo()).isEqualTo("blue"); + assertThat(c.getBar()).isEqualTo(42); BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(bi, "bar"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "bar"), is(false)); + assertThat(hasReadMethodForProperty(bi, "bar")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "bar")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(bi, "bar"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "bar"), is(false)); + assertThat(hasReadMethodForProperty(bi, "bar")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "bar")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "bar"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "bar"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "bar")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "bar")).isTrue(); } @Test @@ -304,11 +300,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse(); } /** @@ -325,8 +321,8 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); assertEquals(hasWriteMethodForProperty(bi, "foo"), hasWriteMethodForProperty(ebi, "foo")); } @@ -340,8 +336,8 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); assertEquals(hasIndexedWriteMethodForProperty(bi, "foos"), hasIndexedWriteMethodForProperty(ebi, "foos")); } @@ -359,11 +355,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse(); } @Test @@ -376,11 +372,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse(); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isFalse(); } @Test @@ -394,11 +390,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); } @Test @@ -412,11 +408,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true)); + assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isTrue(); - assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasWriteMethodForProperty(ebi, "foos")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue(); } @Test @@ -432,15 +428,15 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foos")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue(); } @Test @@ -460,15 +456,15 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(true)); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue(); } @Test @@ -483,14 +479,14 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); // interesting! standard Inspector picks up non-void return types on indexed write methods by default - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue(); } @Test @@ -507,20 +503,20 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse(); // again as above, standard Inspector picks up non-void return types on indexed write methods by default - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse(); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue(); } @Test @@ -535,16 +531,16 @@ public class ExtendedBeanInfoTests { } BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse(); BeanInfo ebi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isFalse(); } { // variant with non-standard write method @SuppressWarnings("unused") @@ -556,16 +552,16 @@ public class ExtendedBeanInfoTests { } BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); - assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); - assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isFalse(); } } @@ -597,18 +593,18 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); - assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length)); + assertThat(ebi.getPropertyDescriptors().length).isEqualTo(bi.getPropertyDescriptors().length); } @Test @@ -621,11 +617,11 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isTrue(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); } /** @@ -642,7 +638,7 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(ebi.getPropertyDescriptors(), equalTo(bi.getPropertyDescriptors())); + assertThat(ebi.getPropertyDescriptors()).isEqualTo(bi.getPropertyDescriptors()); } @Test @@ -653,20 +649,20 @@ public class ExtendedBeanInfoTests { } BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { if (pd.getName().equals("foo")) { - assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); + assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class)); return; } } @@ -681,20 +677,20 @@ public class ExtendedBeanInfoTests { } BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); + assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); + assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { if (pd.getName().equals("foo")) { - assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); + assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class)); return; } } @@ -717,22 +713,22 @@ public class ExtendedBeanInfoTests { } BeanInfo bi = Introspector.getBeanInfo(C.class); - assertThat(hasReadMethodForProperty(bi, "dateFormat"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "dateFormat"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat"), is(false)); + assertThat(hasReadMethodForProperty(bi, "dateFormat")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "dateFormat")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "dateFormat"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "dateFormat"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat"), is(false)); + assertThat(hasReadMethodForProperty(bi, "dateFormat")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "dateFormat")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "dateFormat"), is(false)); - assertThat(hasWriteMethodForProperty(ebi, "dateFormat"), is(true)); - assertThat(hasIndexedReadMethodForProperty(ebi, "dateFormat"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "dateFormat")).isFalse(); + assertThat(hasWriteMethodForProperty(ebi, "dateFormat")).isTrue(); + assertThat(hasIndexedReadMethodForProperty(ebi, "dateFormat")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat")).isFalse(); } @Test @@ -740,7 +736,7 @@ public class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(TestBean.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length)); + assertThat(ebi.getPropertyDescriptors().length).isEqualTo(bi.getPropertyDescriptors().length); } @Test @@ -759,8 +755,8 @@ public class ExtendedBeanInfoTests { break; } } - assertThat(found, is(true)); - assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length+1)); + assertThat(found).isTrue(); + assertThat(ebi.getPropertyDescriptors().length).isEqualTo(bi.getPropertyDescriptors().length+1); } /** @@ -773,8 +769,7 @@ public class ExtendedBeanInfoTests { BeanInfo ebi = new ExtendedBeanInfo(bi); for (int i = 0; i < bi.getPropertyDescriptors().length; i++) { - assertThat("element " + i + " in BeanInfo and ExtendedBeanInfo propertyDescriptor arrays do not match", - ebi.getPropertyDescriptors()[i].getName(), equalTo(bi.getPropertyDescriptors()[i].getName())); + assertThat(ebi.getPropertyDescriptors()[i].getName()).isEqualTo(bi.getPropertyDescriptors()[i].getName()); } } @@ -782,19 +777,19 @@ public class ExtendedBeanInfoTests { public void propertyDescriptorComparator() throws IntrospectionException { ExtendedBeanInfo.PropertyDescriptorComparator c = new ExtendedBeanInfo.PropertyDescriptorComparator(); - assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("a", null, null)), equalTo(0)); - assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abc", null, null)), equalTo(0)); - assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("b", null, null)), lessThan(0)); - assertThat(c.compare(new PropertyDescriptor("b", null, null), new PropertyDescriptor("a", null, null)), greaterThan(0)); - assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abd", null, null)), lessThan(0)); - assertThat(c.compare(new PropertyDescriptor("xyz", null, null), new PropertyDescriptor("123", null, null)), greaterThan(0)); - assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("abc", null, null)), lessThan(0)); - assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("a", null, null)), greaterThan(0)); - assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("b", null, null)), lessThan(0)); + assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("a", null, null))).isEqualTo(0); + assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abc", null, null))).isEqualTo(0); + assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("b", null, null))).isLessThan(0); + assertThat(c.compare(new PropertyDescriptor("b", null, null), new PropertyDescriptor("a", null, null))).isGreaterThan(0); + assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abd", null, null))).isLessThan(0); + assertThat(c.compare(new PropertyDescriptor("xyz", null, null), new PropertyDescriptor("123", null, null))).isGreaterThan(0); + assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("abc", null, null))).isLessThan(0); + assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("a", null, null))).isGreaterThan(0); + assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("b", null, null))).isLessThan(0); - assertThat(c.compare(new PropertyDescriptor(" ", null, null), new PropertyDescriptor("a", null, null)), lessThan(0)); - assertThat(c.compare(new PropertyDescriptor("1", null, null), new PropertyDescriptor("a", null, null)), lessThan(0)); - assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("A", null, null)), greaterThan(0)); + assertThat(c.compare(new PropertyDescriptor(" ", null, null), new PropertyDescriptor("a", null, null))).isLessThan(0); + assertThat(c.compare(new PropertyDescriptor("1", null, null), new PropertyDescriptor("a", null, null))).isLessThan(0); + assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("A", null, null))).isGreaterThan(0); } @Test @@ -830,11 +825,11 @@ public class ExtendedBeanInfoTests { // helps out here, and is now put into use in ExtendedBeanInfo as well. BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(hasReadMethodForProperty(bi, "targetMethod"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "targetMethod"), is(false)); + assertThat(hasReadMethodForProperty(bi, "targetMethod")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "targetMethod")).isFalse(); - assertThat(hasReadMethodForProperty(ebi, "targetMethod"), is(true)); - assertThat(hasWriteMethodForProperty(ebi, "targetMethod"), is(false)); + assertThat(hasReadMethodForProperty(ebi, "targetMethod")).isTrue(); + assertThat(hasWriteMethodForProperty(ebi, "targetMethod")).isFalse(); } @Test @@ -864,27 +859,27 @@ public class ExtendedBeanInfoTests { public void shouldSupportStaticWriteMethod() throws IntrospectionException { { BeanInfo bi = Introspector.getBeanInfo(WithStaticWriteMethod.class); - assertThat(hasReadMethodForProperty(bi, "prop1"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "prop1"), is(false)); - assertThat(hasIndexedReadMethodForProperty(bi, "prop1"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "prop1"), is(false)); + assertThat(hasReadMethodForProperty(bi, "prop1")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "prop1")).isFalse(); + assertThat(hasIndexedReadMethodForProperty(bi, "prop1")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "prop1")).isFalse(); } { BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(WithStaticWriteMethod.class)); - assertThat(hasReadMethodForProperty(bi, "prop1"), is(false)); - assertThat(hasWriteMethodForProperty(bi, "prop1"), is(true)); - assertThat(hasIndexedReadMethodForProperty(bi, "prop1"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "prop1"), is(false)); + assertThat(hasReadMethodForProperty(bi, "prop1")).isFalse(); + assertThat(hasWriteMethodForProperty(bi, "prop1")).isTrue(); + assertThat(hasIndexedReadMethodForProperty(bi, "prop1")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "prop1")).isFalse(); } } @Test // SPR-12434 public void shouldDetectValidPropertiesAndIgnoreInvalidProperties() throws IntrospectionException { BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(java.awt.Window.class)); - assertThat(hasReadMethodForProperty(bi, "locationByPlatform"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "locationByPlatform"), is(true)); - assertThat(hasIndexedReadMethodForProperty(bi, "locationByPlatform"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(bi, "locationByPlatform"), is(false)); + assertThat(hasReadMethodForProperty(bi, "locationByPlatform")).isTrue(); + assertThat(hasWriteMethodForProperty(bi, "locationByPlatform")).isTrue(); + assertThat(hasIndexedReadMethodForProperty(bi, "locationByPlatform")).isFalse(); + assertThat(hasIndexedWriteMethodForProperty(bi, "locationByPlatform")).isFalse(); } 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 9fc958495d..afca39f342 100644 --- a/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java @@ -20,10 +20,8 @@ import java.util.Iterator; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -138,17 +136,17 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("foo", "bar"); - assertThat(pvs.stream(), notNullValue()); - assertThat(pvs.stream().count(), is(1L)); - assertThat(pvs.stream().anyMatch(pv -> "foo".equals(pv.getName()) && "bar".equals(pv.getValue())), is(true)); - assertThat(pvs.stream().anyMatch(pv -> "bar".equals(pv.getName()) && "foo".equals(pv.getValue())), is(false)); + assertThat(pvs.stream()).isNotNull(); + assertThat(pvs.stream().count()).isEqualTo(1L); + assertThat(pvs.stream().anyMatch(pv -> "foo".equals(pv.getName()) && "bar".equals(pv.getValue()))).isTrue(); + assertThat(pvs.stream().anyMatch(pv -> "bar".equals(pv.getName()) && "foo".equals(pv.getValue()))).isFalse(); } @Test public void streamIsEmptyForEmptyValues() { MutablePropertyValues pvs = new MutablePropertyValues(); - assertThat(pvs.stream(), notNullValue()); - assertThat(pvs.stream().count(), is(0L)); + assertThat(pvs.stream()).isNotNull(); + assertThat(pvs.stream().count()).isEqualTo(0L); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/PropertyMatchesTests.java b/spring-beans/src/test/java/org/springframework/beans/PropertyMatchesTests.java index 2a6e8f6a84..ec2ee7a5fd 100644 --- a/spring-beans/src/test/java/org/springframework/beans/PropertyMatchesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/PropertyMatchesTests.java @@ -18,11 +18,12 @@ package org.springframework.beans; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.hasItemInArray; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; + + + + + /** * Tests for {@link PropertyMatches}. @@ -34,93 +35,93 @@ public class PropertyMatchesTests { @Test public void simpleBeanPropertyTypo() { PropertyMatches matches = PropertyMatches.forProperty("naem", SampleBeanProperties.class); - assertThat(matches.getPossibleMatches(), hasItemInArray("name")); + assertThat(matches.getPossibleMatches()).contains("name"); } @Test public void complexBeanPropertyTypo() { PropertyMatches matches = PropertyMatches.forProperty("desriptn", SampleBeanProperties.class); - assertThat(matches.getPossibleMatches(), emptyArray()); + assertThat(matches.getPossibleMatches()).isEmpty(); } @Test public void unknownBeanProperty() { PropertyMatches matches = PropertyMatches.forProperty("unknown", SampleBeanProperties.class); - assertThat(matches.getPossibleMatches(), emptyArray()); + assertThat(matches.getPossibleMatches()).isEmpty(); } @Test public void severalMatchesBeanProperty() { PropertyMatches matches = PropertyMatches.forProperty("counter", SampleBeanProperties.class); - assertThat(matches.getPossibleMatches(), hasItemInArray("counter1")); - assertThat(matches.getPossibleMatches(), hasItemInArray("counter2")); - assertThat(matches.getPossibleMatches(), hasItemInArray("counter3")); + assertThat(matches.getPossibleMatches()).contains("counter1"); + assertThat(matches.getPossibleMatches()).contains("counter2"); + assertThat(matches.getPossibleMatches()).contains("counter3"); } @Test public void simpleBeanPropertyErrorMessage() { PropertyMatches matches = PropertyMatches.forProperty("naem", SampleBeanProperties.class); String msg = matches.buildErrorMessage(); - assertThat(msg, containsString("naem")); - assertThat(msg, containsString("name")); - assertThat(msg, containsString("setter")); - assertThat(msg, not(containsString("field"))); + assertThat(msg).contains("naem"); + assertThat(msg).contains("name"); + assertThat(msg).contains("setter"); + assertThat(msg).doesNotContain("field"); } @Test public void complexBeanPropertyErrorMessage() { PropertyMatches matches = PropertyMatches.forProperty("counter", SampleBeanProperties.class); String msg = matches.buildErrorMessage(); - assertThat(msg, containsString("counter")); - assertThat(msg, containsString("counter1")); - assertThat(msg, containsString("counter2")); - assertThat(msg, containsString("counter3")); + assertThat(msg).contains("counter"); + assertThat(msg).contains("counter1"); + assertThat(msg).contains("counter2"); + assertThat(msg).contains("counter3"); } @Test public void simpleFieldPropertyTypo() { PropertyMatches matches = PropertyMatches.forField("naem", SampleFieldProperties.class); - assertThat(matches.getPossibleMatches(), hasItemInArray("name")); + assertThat(matches.getPossibleMatches()).contains("name"); } @Test public void complexFieldPropertyTypo() { PropertyMatches matches = PropertyMatches.forField("desriptn", SampleFieldProperties.class); - assertThat(matches.getPossibleMatches(), emptyArray()); + assertThat(matches.getPossibleMatches()).isEmpty(); } @Test public void unknownFieldProperty() { PropertyMatches matches = PropertyMatches.forField("unknown", SampleFieldProperties.class); - assertThat(matches.getPossibleMatches(), emptyArray()); + assertThat(matches.getPossibleMatches()).isEmpty(); } @Test public void severalMatchesFieldProperty() { PropertyMatches matches = PropertyMatches.forField("counter", SampleFieldProperties.class); - assertThat(matches.getPossibleMatches(), hasItemInArray("counter1")); - assertThat(matches.getPossibleMatches(), hasItemInArray("counter2")); - assertThat(matches.getPossibleMatches(), hasItemInArray("counter3")); + assertThat(matches.getPossibleMatches()).contains("counter1"); + assertThat(matches.getPossibleMatches()).contains("counter2"); + assertThat(matches.getPossibleMatches()).contains("counter3"); } @Test public void simpleFieldPropertyErrorMessage() { PropertyMatches matches = PropertyMatches.forField("naem", SampleFieldProperties.class); String msg = matches.buildErrorMessage(); - assertThat(msg, containsString("naem")); - assertThat(msg, containsString("name")); - assertThat(msg, containsString("field")); - assertThat(msg, not(containsString("setter"))); + assertThat(msg).contains("naem"); + assertThat(msg).contains("name"); + assertThat(msg).contains("field"); + assertThat(msg).doesNotContain("setter"); } @Test public void complexFieldPropertyErrorMessage() { PropertyMatches matches = PropertyMatches.forField("counter", SampleFieldProperties.class); String msg = matches.buildErrorMessage(); - assertThat(msg, containsString("counter")); - assertThat(msg, containsString("counter1")); - assertThat(msg, containsString("counter2")); - assertThat(msg, containsString("counter3")); + assertThat(msg).contains("counter"); + assertThat(msg).contains("counter1"); + assertThat(msg).contains("counter2"); + assertThat(msg).contains("counter3"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/SimplePropertyDescriptorTests.java b/spring-beans/src/test/java/org/springframework/beans/SimplePropertyDescriptorTests.java index 5ed59fa00b..41dbec4bd9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/SimplePropertyDescriptorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/SimplePropertyDescriptorTests.java @@ -23,11 +23,8 @@ import java.lang.reflect.Method; import org.junit.Test; -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Chris Beams @@ -39,8 +36,8 @@ public class SimplePropertyDescriptorTests { public void toStringOutput() throws IntrospectionException, SecurityException, NoSuchMethodException { { Object pd = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null); - assertThat(pd.toString(), containsString( - "PropertyDescriptor[name=foo, propertyType=null, readMethod=null")); + assertThat(pd.toString()).contains( + "PropertyDescriptor[name=foo, propertyType=null, readMethod=null"); } { class C { @@ -49,15 +46,15 @@ public class SimplePropertyDescriptorTests { } Method m = C.class.getMethod("setFoo", String.class); Object pd = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, m); - assertThat(pd.toString(), allOf( - containsString("PropertyDescriptor[name=foo"), - containsString("propertyType=class java.lang.String"), - containsString("readMethod=null, writeMethod=public java.lang.Object"))); + assertThat(pd.toString()).contains( + "PropertyDescriptor[name=foo", + "propertyType=class java.lang.String", + "readMethod=null, writeMethod=public java.lang.Object"); } { Object pd = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null); - assertThat(pd.toString(), containsString( - "PropertyDescriptor[name=foo, propertyType=null, indexedPropertyType=null")); + assertThat(pd.toString()).contains( + "PropertyDescriptor[name=foo, propertyType=null, indexedPropertyType=null"); } { class C { @@ -66,21 +63,21 @@ public class SimplePropertyDescriptorTests { } Method m = C.class.getMethod("setFoo", int.class, String.class); Object pd = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, m); - assertThat(pd.toString(), allOf( - containsString("PropertyDescriptor[name=foo, propertyType=null"), - containsString("indexedPropertyType=class java.lang.String"), - containsString("indexedWriteMethod=public java.lang.Object"))); + assertThat(pd.toString()).contains( + "PropertyDescriptor[name=foo, propertyType=null", + "indexedPropertyType=class java.lang.String", + "indexedWriteMethod=public java.lang.Object"); } } @Test public void nonIndexedEquality() throws IntrospectionException, SecurityException, NoSuchMethodException { Object pd1 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null); - assertThat(pd1, equalTo(pd1)); + assertThat(pd1).isEqualTo(pd1); Object pd2 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null); - assertThat(pd1, equalTo(pd2)); - assertThat(pd2, equalTo(pd1)); + assertThat(pd1).isEqualTo(pd2); + assertThat(pd2).isEqualTo(pd1); @SuppressWarnings("unused") class C { @@ -89,35 +86,35 @@ public class SimplePropertyDescriptorTests { } Method wm1 = C.class.getMethod("setFoo", String.class); Object pd3 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, wm1); - assertThat(pd1, not(equalTo(pd3))); - assertThat(pd3, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd3); + assertThat(pd3).isNotEqualTo(pd1); Method rm1 = C.class.getMethod("getFoo"); Object pd4 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", rm1, null); - assertThat(pd1, not(equalTo(pd4))); - assertThat(pd4, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd4); + assertThat(pd4).isNotEqualTo(pd1); Object pd5 = new PropertyDescriptor("foo", null, null); - assertThat(pd1, equalTo(pd5)); - assertThat(pd5, equalTo(pd1)); + assertThat(pd1).isEqualTo(pd5); + assertThat(pd5).isEqualTo(pd1); Object pd6 = "not a PD"; - assertThat(pd1, not(equalTo(pd6))); - assertThat(pd6, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd6); + assertThat(pd6).isNotEqualTo(pd1); Object pd7 = null; - assertThat(pd1, not(equalTo(pd7))); - assertThat(pd7, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd7); + assertThat(pd7).isNotEqualTo(pd1); } @Test public void indexedEquality() throws IntrospectionException, SecurityException, NoSuchMethodException { Object pd1 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null); - assertThat(pd1, equalTo(pd1)); + assertThat(pd1).isEqualTo(pd1); Object pd2 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null); - assertThat(pd1, equalTo(pd2)); - assertThat(pd2, equalTo(pd1)); + assertThat(pd1).isEqualTo(pd2); + assertThat(pd2).isEqualTo(pd1); @SuppressWarnings("unused") class C { @@ -126,25 +123,25 @@ public class SimplePropertyDescriptorTests { } Method wm1 = C.class.getMethod("setFoo", int.class, String.class); Object pd3 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, wm1); - assertThat(pd1, not(equalTo(pd3))); - assertThat(pd3, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd3); + assertThat(pd3).isNotEqualTo(pd1); Method rm1 = C.class.getMethod("getFoo", int.class); Object pd4 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, rm1, null); - assertThat(pd1, not(equalTo(pd4))); - assertThat(pd4, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd4); + assertThat(pd4).isNotEqualTo(pd1); Object pd5 = new IndexedPropertyDescriptor("foo", null, null, null, null); - assertThat(pd1, equalTo(pd5)); - assertThat(pd5, equalTo(pd1)); + assertThat(pd1).isEqualTo(pd5); + assertThat(pd5).isEqualTo(pd1); Object pd6 = "not a PD"; - assertThat(pd1, not(equalTo(pd6))); - assertThat(pd6, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd6); + assertThat(pd6).isNotEqualTo(pd1); Object pd7 = null; - assertThat(pd1, not(equalTo(pd7))); - assertThat(pd7, not(equalTo(pd1))); + assertThat(pd1).isNotEqualTo(pd7); + assertThat(pd7).isNotEqualTo(pd1); } } 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 54da987734..1574b77355 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -103,8 +103,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -1380,7 +1378,7 @@ public class DefaultListableBeanFactoryTests { parent.registerBeanDefinition("bd1", bd1); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent); TestBean bean = lbf.getBean(TestBean.class); - assertThat(bean.getBeanName(), equalTo("bd1")); + assertThat(bean.getBeanName()).isEqualTo("bd1"); } @Test @@ -1404,7 +1402,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd2", bd2); TestBean bean = lbf.getBean(TestBean.class); - assertThat(bean.getBeanName(), equalTo("bd2")); + assertThat(bean.getBeanName()).isEqualTo("bd2"); assertFalse(lbf.containsSingleton("bd1")); } @@ -1453,7 +1451,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd3", bd3); lbf.preInstantiateSingletons(); TestBean bean = lbf.getBean(TestBean.class); - assertThat(bean.getBeanName(), equalTo("bd1")); + assertThat(bean.getBeanName()).isEqualTo("bd1"); } @Test @@ -1470,7 +1468,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd4", bd4); lbf.preInstantiateSingletons(); TestBean bean = lbf.getBean(TestBeanRecipient.class).testBean; - assertThat(bean.getBeanName(), equalTo("bd1")); + assertThat(bean.getBeanName()).isEqualTo("bd1"); } @Test @@ -1496,7 +1494,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd2", bd2); TestBean bean = lbf.getBean(TestBean.class); - assertThat(bean.getBeanName(), equalTo("bd1")); + assertThat(bean.getBeanName()).isEqualTo("bd1"); } @Test @@ -1509,7 +1507,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd2", bd2); TestBean bean = lbf.getBean(TestBean.class); - assertThat(bean.getBeanName(), equalTo("bd2")); + assertThat(bean.getBeanName()).isEqualTo("bd2"); } @Test @@ -1554,25 +1552,25 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent); ConstructorDependency bean = lbf.getBean(ConstructorDependency.class); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(99)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(99); bean = lbf.getBean(ConstructorDependency.class, 42); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(42)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(42); ObjectProvider provider = lbf.getBeanProvider(ConstructorDependency.class); bean = provider.getObject(); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(99)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(99); bean = provider.getObject(42); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(42)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(42); bean = provider.getIfAvailable(); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(99)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(99); bean = provider.getIfUnique(); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(99)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(99); } @Test @@ -1627,25 +1625,25 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd2", bd2); ConstructorDependency bean = lbf.getBean(ConstructorDependency.class); - assertThat(bean.beanName, equalTo("bd2")); - assertThat(bean.spouseAge, equalTo(43)); + assertThat(bean.beanName).isEqualTo("bd2"); + assertThat(bean.spouseAge).isEqualTo(43); bean = lbf.getBean(ConstructorDependency.class, 42); - assertThat(bean.beanName, equalTo("bd2")); - assertThat(bean.spouseAge, equalTo(42)); + assertThat(bean.beanName).isEqualTo("bd2"); + assertThat(bean.spouseAge).isEqualTo(42); ObjectProvider provider = lbf.getBeanProvider(ConstructorDependency.class); bean = provider.getObject(); - assertThat(bean.beanName, equalTo("bd2")); - assertThat(bean.spouseAge, equalTo(43)); + assertThat(bean.beanName).isEqualTo("bd2"); + assertThat(bean.spouseAge).isEqualTo(43); bean = provider.getObject(42); - assertThat(bean.beanName, equalTo("bd2")); - assertThat(bean.spouseAge, equalTo(42)); + assertThat(bean.beanName).isEqualTo("bd2"); + assertThat(bean.spouseAge).isEqualTo(42); bean = provider.getIfAvailable(); - assertThat(bean.beanName, equalTo("bd2")); - assertThat(bean.spouseAge, equalTo(43)); + assertThat(bean.beanName).isEqualTo("bd2"); + assertThat(bean.spouseAge).isEqualTo(43); bean = provider.getIfUnique(); - assertThat(bean.beanName, equalTo("bd2")); - assertThat(bean.spouseAge, equalTo(43)); + assertThat(bean.beanName).isEqualTo("bd2"); + assertThat(bean.spouseAge).isEqualTo(43); Set resolved = new HashSet<>(); for (ConstructorDependency instance : provider) { @@ -1693,7 +1691,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("na1", na1); ConstructorDependency actual = lbf.getBean(ConstructorDependency.class, 42); // na1 was filtered - assertThat(actual.beanName, equalTo("bd1")); + assertThat(actual.beanName).isEqualTo("bd1"); lbf.registerBeanDefinition("bd2", bd2); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> @@ -1727,8 +1725,8 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd2", bd2); ConstructorDependency bean = lbf.getBean(ConstructorDependency.class, 42); - assertThat(bean.beanName, equalTo("bd1")); - assertThat(bean.spouseAge, equalTo(42)); + assertThat(bean.beanName).isEqualTo("bd1"); + assertThat(bean.spouseAge).isEqualTo(42); assertEquals(1, lbf.getBeanNamesForType(ConstructorDependency.class).length); assertEquals(1, lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length); @@ -1902,7 +1900,7 @@ public class DefaultListableBeanFactoryTests { DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - assertThat(bean.getSpouse(), equalTo(lbf.getBean("test"))); + assertThat(bean.getSpouse()).isEqualTo(lbf.getBean("test")); } @Test @@ -1930,7 +1928,7 @@ public class DefaultListableBeanFactoryTests { DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - assertThat(bean.getSpouse(), equalTo(lbf.getBean("test"))); + assertThat(bean.getSpouse()).isEqualTo(lbf.getBean("test")); } @Test @@ -1959,7 +1957,7 @@ public class DefaultListableBeanFactoryTests { DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - assertThat(bean.getSpouse(), equalTo(lbf.getBean("spouse"))); + assertThat(bean.getSpouse()).isEqualTo(lbf.getBean("spouse")); } @Test @@ -2768,8 +2766,8 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("abs", BeanDefinitionBuilder .rootBeanDefinition(TestBean.class).setAbstract(true).getBeanDefinition()); - assertThat(bf.containsBean("abs"), equalTo(true)); - assertThat(bf.containsBean("bogus"), equalTo(false)); + assertThat(bf.containsBean("abs")).isEqualTo(true); + assertThat(bf.containsBean("bogus")).isEqualTo(false); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java index c77afa72fc..4986d5c4c6 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java @@ -25,8 +25,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; /** @@ -47,7 +46,7 @@ public class FactoryBeanLookupTests { @Test public void factoryBeanLookupByNameDereferencing() { Object fooFactory = beanFactory.getBean("&fooFactory"); - assertThat(fooFactory, instanceOf(FooFactoryBean.class)); + assertThat(fooFactory).isInstanceOf(FooFactoryBean.class); } @Test @@ -65,7 +64,7 @@ public class FactoryBeanLookupTests { @Test public void factoryBeanObjectLookupByName() { Object fooFactory = beanFactory.getBean("fooFactory"); - assertThat(fooFactory, instanceOf(Foo.class)); + assertThat(fooFactory).isInstanceOf(Foo.class); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java index 7cccd7bb74..01e337a728 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java @@ -28,10 +28,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.registerWithGeneratedName; @@ -101,8 +98,8 @@ public class PropertyPlaceholderConfigurerTests { registerWithGeneratedName(p1BeanDef, bf); ppc.postProcessBeanFactory(bf); TestBean bean = bf.getBean(TestBean.class); - assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); - assertThat(bean.getSex(), equalTo("systemValue")); + assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); + assertThat(bean.getSex()).isEqualTo("systemValue"); System.clearProperty("otherKey"); } @@ -112,7 +109,7 @@ public class PropertyPlaceholderConfigurerTests { registerWithGeneratedName(p1BeanDef, bf); ppc.postProcessBeanFactory(bf); TestBean bean = bf.getBean(TestBean.class); - assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); + assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); } @Test @@ -120,7 +117,7 @@ public class PropertyPlaceholderConfigurerTests { registerWithGeneratedName(p1BeanDef, bf); ppc.postProcessBeanFactory(bf); TestBean bean = bf.getBean(TestBean.class); - assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); + assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); } @Test @@ -129,7 +126,7 @@ public class PropertyPlaceholderConfigurerTests { ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); ppc.postProcessBeanFactory(bf); TestBean bean = bf.getBean(TestBean.class); - assertThat(bean.getName(), equalTo(P1_SYSTEM_PROPS_VAL)); + assertThat(bean.getName()).isEqualTo(P1_SYSTEM_PROPS_VAL); } @Test @@ -140,7 +137,7 @@ public class PropertyPlaceholderConfigurerTests { ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); ppc.postProcessBeanFactory(bf); TestBean bean = bf.getBean(TestBean.class); - assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); // has to resort to local props + assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); // has to resort to local props } /** @@ -177,11 +174,11 @@ public class PropertyPlaceholderConfigurerTests { ppc2.postProcessBeanFactory(bf); TestBean p1Bean = bf.getBean("p1Bean", TestBean.class); - assertThat(p1Bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); + assertThat(p1Bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); TestBean p2Bean = bf.getBean("p2Bean", TestBean.class); - assertThat(p2Bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); - assertThat(p2Bean.getCountry(), equalTo(P2_SYSTEM_PROPS_VAL)); + assertThat(p2Bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); + assertThat(p2Bean.getCountry()).isEqualTo(P2_SYSTEM_PROPS_VAL); System.clearProperty(P2); } @@ -205,8 +202,8 @@ public class PropertyPlaceholderConfigurerTests { System.clearProperty("key1"); System.clearProperty("key2"); - assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value")); - assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("systemKey1Value"); + assertThat(bf.getBean(TestBean.class).getSex()).isEqualTo("${key2}"); } @Test @@ -219,7 +216,7 @@ public class PropertyPlaceholderConfigurerTests { .addPropertyValue("name", "${my.name}") .getBeanDefinition()); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), nullValue()); + assertThat(bf.getBean(TestBean.class).getName()).isNull(); System.clearProperty("my.name"); } @@ -232,7 +229,7 @@ public class PropertyPlaceholderConfigurerTests { .addPropertyValue("name", "${my.name}") .getBeanDefinition()); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue ")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo(" myValue "); System.clearProperty("my.name"); } @@ -246,7 +243,7 @@ public class PropertyPlaceholderConfigurerTests { .addPropertyValue("name", "${my.name}") .getBeanDefinition()); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("myValue"); System.clearProperty("my.name"); } 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 6eced27caa..a3ce6db697 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 @@ -30,11 +30,12 @@ import org.springframework.beans.factory.config.YamlProcessor.ResolutionMethod; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ClassPathResource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; + + + + /** * Tests for {@link YamlPropertiesFactoryBean}. @@ -50,8 +51,8 @@ public class YamlPropertiesFactoryBeanTests { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bar")); - assertThat(properties.getProperty("spam.foo"), equalTo("baz")); + assertThat(properties.getProperty("foo")).isEqualTo("bar"); + assertThat(properties.getProperty("spam.foo")).isEqualTo("baz"); } @Test @@ -71,9 +72,9 @@ public class YamlPropertiesFactoryBeanTests { new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes()), new ByteArrayResource("foo:\n bar: spam".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bar")); - assertThat(properties.getProperty("spam.foo"), equalTo("baz")); - assertThat(properties.getProperty("foo.bar"), equalTo("spam")); + assertThat(properties.getProperty("foo")).isEqualTo("bar"); + assertThat(properties.getProperty("spam.foo")).isEqualTo("baz"); + assertThat(properties.getProperty("foo.bar")).isEqualTo("spam"); } @Test @@ -100,8 +101,8 @@ public class YamlPropertiesFactoryBeanTests { factory.setResources(new ByteArrayResource( "foo: bar\nspam: baz\n---\nfoo: bag".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bag")); - assertThat(properties.getProperty("spam"), equalTo("baz")); + assertThat(properties.getProperty("foo")).isEqualTo("bag"); + assertThat(properties.getProperty("spam")).isEqualTo("baz"); } @Test @@ -112,8 +113,8 @@ public class YamlPropertiesFactoryBeanTests { factory.setDocumentMatchers(properties -> ("bag".equals(properties.getProperty("foo")) ? MatchStatus.FOUND : MatchStatus.NOT_FOUND)); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bag")); - assertThat(properties.getProperty("spam"), equalTo("bad")); + assertThat(properties.getProperty("foo")).isEqualTo("bag"); + assertThat(properties.getProperty("spam")).isEqualTo("bad"); } @Test @@ -130,9 +131,9 @@ public class YamlPropertiesFactoryBeanTests { MatchStatus.FOUND : MatchStatus.NOT_FOUND); }); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bag")); - assertThat(properties.getProperty("spam"), equalTo("bad")); - assertThat(properties.getProperty("one"), equalTo("two")); + assertThat(properties.getProperty("foo")).isEqualTo("bag"); + assertThat(properties.getProperty("spam")).isEqualTo("bad"); + assertThat(properties.getProperty("one")).isEqualTo("two"); } @Test @@ -152,9 +153,9 @@ public class YamlPropertiesFactoryBeanTests { } }); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bag")); - assertThat(properties.getProperty("spam"), equalTo("bad")); - assertThat(properties.getProperty("one"), nullValue()); + assertThat(properties.getProperty("foo")).isEqualTo("bag"); + assertThat(properties.getProperty("spam")).isEqualTo("bad"); + assertThat(properties.getProperty("one")).isNull(); } @Test @@ -171,9 +172,9 @@ public class YamlPropertiesFactoryBeanTests { MatchStatus.FOUND : MatchStatus.NOT_FOUND); }); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bag")); - assertThat(properties.getProperty("spam"), equalTo("bad")); - assertThat(properties.getProperty("one"), equalTo("two")); + assertThat(properties.getProperty("foo")).isEqualTo("bag"); + assertThat(properties.getProperty("spam")).isEqualTo("bad"); + assertThat(properties.getProperty("one")).isEqualTo("two"); } @Test @@ -182,7 +183,7 @@ public class YamlPropertiesFactoryBeanTests { factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE); factory.setResources(new ClassPathResource("no-such-file.yml")); Properties properties = factory.getObject(); - assertThat(properties.size(), equalTo(0)); + assertThat(properties.size()).isEqualTo(0); } @Test @@ -190,8 +191,8 @@ public class YamlPropertiesFactoryBeanTests { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource("foo: bar\nspam:".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo"), equalTo("bar")); - assertThat(properties.getProperty("spam"), equalTo("")); + assertThat(properties.getProperty("foo")).isEqualTo("bar"); + assertThat(properties.getProperty("spam")).isEqualTo(""); } @Test @@ -199,8 +200,8 @@ public class YamlPropertiesFactoryBeanTests { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource("a: alpha\ntest: []".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("a"), equalTo("alpha")); - assertThat(properties.getProperty("test"), equalTo("")); + assertThat(properties.getProperty("a")).isEqualTo("alpha"); + assertThat(properties.getProperty("test")).isEqualTo(""); } @Test @@ -208,9 +209,9 @@ public class YamlPropertiesFactoryBeanTests { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource("foo:\n- bar\n- baz".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo[0]"), equalTo("bar")); - assertThat(properties.getProperty("foo[1]"), equalTo("baz")); - assertThat(properties.get("foo"), is(nullValue())); + assertThat(properties.getProperty("foo[0]")).isEqualTo("bar"); + assertThat(properties.getProperty("foo[1]")).isEqualTo("baz"); + assertThat(properties.get("foo")).isNull(); } @Test @@ -218,9 +219,9 @@ public class YamlPropertiesFactoryBeanTests { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource("foo:\n- 1\n- 2".getBytes())); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo[0]"), equalTo("1")); - assertThat(properties.getProperty("foo[1]"), equalTo("2")); - assertThat(properties.get("foo"), is(nullValue())); + assertThat(properties.getProperty("foo[0]")).isEqualTo("1"); + assertThat(properties.getProperty("foo[1]")).isEqualTo("2"); + assertThat(properties.get("foo")).isNull(); } @Test @@ -230,11 +231,11 @@ public class YamlPropertiesFactoryBeanTests { "foo:\n- bar:\n spam: crap\n- baz\n- one: two\n three: four".getBytes() )); Properties properties = factory.getObject(); - assertThat(properties.getProperty("foo[0].bar.spam"), equalTo("crap")); - assertThat(properties.getProperty("foo[1]"), equalTo("baz")); - assertThat(properties.getProperty("foo[2].one"), equalTo("two")); - assertThat(properties.getProperty("foo[2].three"), equalTo("four")); - assertThat(properties.get("foo"), is(nullValue())); + assertThat(properties.getProperty("foo[0].bar.spam")).isEqualTo("crap"); + assertThat(properties.getProperty("foo[1]")).isEqualTo("baz"); + assertThat(properties.getProperty("foo[2].one")).isEqualTo("two"); + assertThat(properties.getProperty("foo[2].three")).isEqualTo("four"); + assertThat(properties.get("foo")).isNull(); } @SuppressWarnings("unchecked") @@ -242,8 +243,8 @@ public class YamlPropertiesFactoryBeanTests { public void testYaml() { Yaml yaml = new Yaml(); Map map = yaml.loadAs("foo: bar\nspam:\n foo: baz", Map.class); - assertThat(map.get("foo"), equalTo("bar")); - assertThat(((Map) map.get("spam")).get("foo"), equalTo("baz")); + assertThat(map.get("foo")).isEqualTo("bar"); + assertThat(((Map) map.get("spam")).get("foo")).isEqualTo("baz"); } } 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 9452c9e8fa..6c4a067828 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 @@ -26,11 +26,8 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor} @@ -56,32 +53,32 @@ public class Spr8954Tests { @Test public void repro() { - assertThat(bf.getBean("foo"), instanceOf(Foo.class)); - assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); - assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + assertThat(bf.getBean("foo")).isInstanceOf(Foo.class); + assertThat(bf.getBean("&foo")).isInstanceOf(FooFactoryBean.class); + assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue(); @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(fbBeans.size(), is(1)); - assertThat(fbBeans.keySet(), hasItem("&foo")); + assertThat(fbBeans).hasSize(1); + assertThat(fbBeans.keySet()).contains("&foo"); Map aiBeans = bf.getBeansOfType(AnInterface.class); - assertThat(aiBeans.size(), is(1)); - assertThat(aiBeans.keySet(), hasItem("&foo")); + assertThat(aiBeans).hasSize(1); + assertThat(aiBeans.keySet()).contains("&foo"); } @Test public void findsBeansByTypeIfNotInstantiated() { - assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue(); @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(1, equalTo(fbBeans.size())); - assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); + assertThat(1).isEqualTo(fbBeans.size()); + assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next()); Map aiBeans = bf.getBeansOfType(AnInterface.class); - assertThat(aiBeans.size(), is(1)); - assertThat(aiBeans.keySet(), hasItem("&foo")); + assertThat(aiBeans).hasSize(1); + assertThat(aiBeans.keySet()).contains("&foo"); } /** @@ -90,11 +87,11 @@ public class Spr8954Tests { @Test public void findsFactoryBeanNameByTypeWithoutInstantiation() { String[] names = bf.getBeanNamesForType(AnInterface.class, false, false); - assertThat(Arrays.asList(names), hasItem("&foo")); + assertThat(Arrays.asList(names)).contains("&foo"); Map beans = bf.getBeansOfType(AnInterface.class, false, false); - assertThat(beans.size(), is(1)); - assertThat(beans.keySet(), hasItem("&foo")); + assertThat(beans).hasSize(1); + assertThat(beans.keySet()).contains("&foo"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java index 1905a8893a..932b1d9b93 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java @@ -22,9 +22,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; + /** * With Spring 3.1, bean id attributes (and all other id attributes across the @@ -56,6 +56,6 @@ public class DuplicateBeanIdTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-multiLevel-context.xml", this.getClass())); TestBean testBean = bf.getBean(TestBean.class); // there should be only one - assertThat(testBean.getName(), equalTo("nested")); + assertThat(testBean.getName()).isEqualTo("nested"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java index 14fa12434e..18acabef81 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java @@ -23,10 +23,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItems; +import static org.assertj.core.api.Assertions.assertThat; + + /** * Tests for propagating enclosing beans element defaults to nested beans elements. @@ -62,11 +61,11 @@ public class NestedBeansElementAttributeRecursionTests { BeanDefinition biz = bf.getBeanDefinition("biz"); BeanDefinition buz = bf.getBeanDefinition("buz"); - assertThat(foo.isLazyInit(), is(false)); - assertThat(bar.isLazyInit(), is(true)); - assertThat(baz.isLazyInit(), is(false)); - assertThat(biz.isLazyInit(), is(true)); - assertThat(buz.isLazyInit(), is(true)); + assertThat(foo.isLazyInit()).isFalse(); + assertThat(bar.isLazyInit()).isTrue(); + assertThat(baz.isLazyInit()).isFalse(); + assertThat(biz.isLazyInit()).isTrue(); + assertThat(buz.isLazyInit()).isTrue(); } @Test @@ -95,19 +94,19 @@ public class NestedBeansElementAttributeRecursionTests { private void assertMerge(DefaultListableBeanFactory bf) { TestBean topLevel = bf.getBean("topLevelConcreteTestBean", TestBean.class); // has the concrete child bean values - assertThat((Iterable) topLevel.getSomeList(), hasItems("charlie", "delta")); + assertThat((Iterable) topLevel.getSomeList()).contains("charlie", "delta"); // but does not merge the parent values - assertThat((Iterable) topLevel.getSomeList(), not(hasItems("alpha", "bravo"))); + assertThat((Iterable) topLevel.getSomeList()).doesNotContain("alpha", "bravo"); TestBean firstLevel = bf.getBean("firstLevelNestedTestBean", TestBean.class); // merges all values - assertThat((Iterable) firstLevel.getSomeList(), - hasItems("charlie", "delta", "echo", "foxtrot")); + assertThat((Iterable) firstLevel.getSomeList()).contains( + "charlie", "delta", "echo", "foxtrot"); TestBean secondLevel = bf.getBean("secondLevelNestedTestBean", TestBean.class); // merges all values - assertThat((Iterable)secondLevel.getSomeList(), - hasItems("charlie", "delta", "echo", "foxtrot", "golf", "hotel")); + assertThat((Iterable)secondLevel.getSomeList()).contains( + "charlie", "delta", "echo", "foxtrot", "golf", "hotel"); } @Test @@ -131,23 +130,23 @@ public class NestedBeansElementAttributeRecursionTests { } private void assertAutowireCandidates(DefaultListableBeanFactory bf) { - assertThat(bf.getBeanDefinition("fooService").isAutowireCandidate(), is(true)); - assertThat(bf.getBeanDefinition("fooRepository").isAutowireCandidate(), is(true)); - assertThat(bf.getBeanDefinition("other").isAutowireCandidate(), is(false)); + assertThat(bf.getBeanDefinition("fooService").isAutowireCandidate()).isTrue(); + assertThat(bf.getBeanDefinition("fooRepository").isAutowireCandidate()).isTrue(); + assertThat(bf.getBeanDefinition("other").isAutowireCandidate()).isFalse(); - assertThat(bf.getBeanDefinition("barService").isAutowireCandidate(), is(true)); - assertThat(bf.getBeanDefinition("fooController").isAutowireCandidate(), is(false)); + assertThat(bf.getBeanDefinition("barService").isAutowireCandidate()).isTrue(); + assertThat(bf.getBeanDefinition("fooController").isAutowireCandidate()).isFalse(); - assertThat(bf.getBeanDefinition("bizRepository").isAutowireCandidate(), is(true)); - assertThat(bf.getBeanDefinition("bizService").isAutowireCandidate(), is(false)); + assertThat(bf.getBeanDefinition("bizRepository").isAutowireCandidate()).isTrue(); + assertThat(bf.getBeanDefinition("bizService").isAutowireCandidate()).isFalse(); - assertThat(bf.getBeanDefinition("bazService").isAutowireCandidate(), is(true)); - assertThat(bf.getBeanDefinition("random").isAutowireCandidate(), is(false)); - assertThat(bf.getBeanDefinition("fooComponent").isAutowireCandidate(), is(false)); - assertThat(bf.getBeanDefinition("fRepository").isAutowireCandidate(), is(false)); + assertThat(bf.getBeanDefinition("bazService").isAutowireCandidate()).isTrue(); + assertThat(bf.getBeanDefinition("random").isAutowireCandidate()).isFalse(); + assertThat(bf.getBeanDefinition("fooComponent").isAutowireCandidate()).isFalse(); + assertThat(bf.getBeanDefinition("fRepository").isAutowireCandidate()).isFalse(); - assertThat(bf.getBeanDefinition("aComponent").isAutowireCandidate(), is(true)); - assertThat(bf.getBeanDefinition("someService").isAutowireCandidate(), is(false)); + assertThat(bf.getBeanDefinition("aComponent").isAutowireCandidate()).isTrue(); + assertThat(bf.getBeanDefinition("someService").isAutowireCandidate()).isFalse(); } @Test @@ -161,17 +160,17 @@ public class NestedBeansElementAttributeRecursionTests { InitDestroyBean beanC = bf.getBean("beanC", InitDestroyBean.class); InitDestroyBean beanD = bf.getBean("beanD", InitDestroyBean.class); - assertThat(beanA.initMethod1Called, is(true)); - assertThat(beanB.initMethod2Called, is(true)); - assertThat(beanC.initMethod3Called, is(true)); - assertThat(beanD.initMethod2Called, is(true)); + assertThat(beanA.initMethod1Called).isTrue(); + assertThat(beanB.initMethod2Called).isTrue(); + assertThat(beanC.initMethod3Called).isTrue(); + assertThat(beanD.initMethod2Called).isTrue(); bf.destroySingletons(); - assertThat(beanA.destroyMethod1Called, is(true)); - assertThat(beanB.destroyMethod2Called, is(true)); - assertThat(beanC.destroyMethod3Called, is(true)); - assertThat(beanD.destroyMethod2Called, is(true)); + assertThat(beanA.destroyMethod1Called).isTrue(); + assertThat(beanB.destroyMethod2Called).isTrue(); + assertThat(beanC.destroyMethod3Called).isTrue(); + assertThat(beanD.destroyMethod2Called).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementTests.java index 3323cf13f9..ec790b2d1a 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementTests.java @@ -24,8 +24,8 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests for new nested beans element support in Spring XML @@ -42,7 +42,7 @@ public class NestedBeansElementTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions(XML); Object foo = bf.getBean("foo"); - assertThat(foo, instanceOf(String.class)); + assertThat(foo).isInstanceOf(String.class); } @Test @@ -58,7 +58,7 @@ public class NestedBeansElementTests { bf.getBean("devOnlyBean"); // should not throw NSBDE Object foo = bf.getBean("foo"); - assertThat(foo, instanceOf(Integer.class)); + assertThat(foo).isInstanceOf(Integer.class); bf.getBean("devOnlyBean"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProfileXmlBeanDefinitionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProfileXmlBeanDefinitionTests.java index 32ff6616b9..e02b6a10cc 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProfileXmlBeanDefinitionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProfileXmlBeanDefinitionTests.java @@ -16,9 +16,7 @@ package org.springframework.beans.factory.xml; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; +import org.assertj.core.api.Condition; import org.junit.Test; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -27,9 +25,8 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ClassPathResource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; /** * Tests various combinations of profile declarations against various profile @@ -71,51 +68,51 @@ public class ProfileXmlBeanDefinitionTests { @Test public void testProfilePermutations() { - assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, DEV_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); + assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, NONE_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, DEV_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget()); - assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, PROD_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); + assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, NONE_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, DEV_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, PROD_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget()); - assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE), not(containsTargetBean())); + assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE)).isNot(containingTarget()); - assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); + assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, DEV_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget()); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, UNKNOWN_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, NONE_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, UNKNOWN_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, DEV_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget()); - assertThat(beanFactoryFor(MULTI_NEGATED_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NEGATED_XML, UNKNOWN_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NEGATED_XML, DEV_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NEGATED_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NEGATED_XML, MULTI_ACTIVE), not(containsTargetBean())); + assertThat(beanFactoryFor(MULTI_NEGATED_XML, NONE_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NEGATED_XML, UNKNOWN_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NEGATED_XML, DEV_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NEGATED_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NEGATED_XML, MULTI_ACTIVE)).isNot(containingTarget()); - assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, UNKNOWN_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); + assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, UNKNOWN_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget()); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, NONE_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, UNKNOWN_ACTIVE), not(containsTargetBean())); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, DEV_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, PROD_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, MULTI_ACTIVE), containsTargetBean()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, NONE_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, UNKNOWN_ACTIVE)).isNot(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, DEV_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, PROD_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, MULTI_ACTIVE)).is(containingTarget()); - assertThat(beanFactoryFor(UNKNOWN_ELIGIBLE_XML, MULTI_ACTIVE), not(containsTargetBean())); + assertThat(beanFactoryFor(UNKNOWN_ELIGIBLE_XML, MULTI_ACTIVE)).isNot(containingTarget()); } @Test @@ -128,7 +125,7 @@ public class ProfileXmlBeanDefinitionTests { reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_ELIGIBLE_XML, getClass())); - assertThat(beanFactory, not(containsTargetBean())); + assertThat(beanFactory).isNot(containingTarget()); } { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @@ -138,14 +135,14 @@ public class ProfileXmlBeanDefinitionTests { reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(CUSTOM_DEFAULT_ELIGIBLE_XML, getClass())); - assertThat(beanFactory, containsTargetBean()); + assertThat(beanFactory).is(containingTarget()); } } @Test public void testDefaultAndNonDefaultProfile() { - assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other"), not(containsTargetBean())); + assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget()); + assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other")).isNot(containingTarget()); { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @@ -155,7 +152,7 @@ public class ProfileXmlBeanDefinitionTests { env.setDefaultProfiles("default"); reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); - assertThat(beanFactory, containsTargetBean()); + assertThat(beanFactory).is(containingTarget()); } { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @@ -165,7 +162,7 @@ public class ProfileXmlBeanDefinitionTests { env.setDefaultProfiles("default"); reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); - assertThat(beanFactory, containsTargetBean()); + assertThat(beanFactory).is(containingTarget()); } { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @@ -175,7 +172,7 @@ public class ProfileXmlBeanDefinitionTests { //env.setDefaultProfiles("default"); reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); - assertThat(beanFactory, containsTargetBean()); + assertThat(beanFactory).is(containingTarget()); } } @@ -190,25 +187,8 @@ public class ProfileXmlBeanDefinitionTests { return beanFactory; } - - private static Matcher containsBeanDefinition(final String beanName) { - return new TypeSafeMatcher() { - - @Override - public void describeTo(Description desc) { - desc.appendText("a BeanDefinitionRegistry containing bean named ") - .appendValue(beanName); - } - - @Override - public boolean matchesSafely(BeanDefinitionRegistry beanFactory) { - return beanFactory.containsBeanDefinition(beanName); - } - - }; + private Condition containingTarget() { + return new Condition<>(registry -> registry.containsBeanDefinition(TARGET_BEAN), "contains target"); } - private static Matcher containsTargetBean() { - return containsBeanDefinition(TARGET_BEAN); - } } 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 20314c0454..3cf8e7931c 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 @@ -60,10 +60,10 @@ import org.springframework.context.index.test.TestCompiler; import org.springframework.stereotype.Component; import org.springframework.util.ClassUtils; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.sameInstance; -import static org.springframework.context.index.processor.Metadata.hasComponent; +import static org.assertj.core.api.Assertions.assertThat; + + + /** * Tests for {@link CandidateComponentsIndexer}. @@ -87,13 +87,13 @@ public class CandidateComponentsIndexerTests { @Test public void noCandidate() { CandidateComponentsMetadata metadata = compile(SampleNone.class); - assertThat(metadata.getItems(), hasSize(0)); + assertThat(metadata.getItems()).hasSize(0); } @Test public void noAnnotation() { CandidateComponentsMetadata metadata = compile(CandidateComponentsIndexerTests.class); - assertThat(metadata.getItems(), hasSize(0)); + assertThat(metadata.getItems()).hasSize(0); } @Test @@ -171,7 +171,7 @@ public class CandidateComponentsIndexerTests { public void packageInfo() { CandidateComponentsMetadata metadata = compile( "org/springframework/context/index/sample/jpa/package-info"); - assertThat(metadata, hasComponent( + assertThat(metadata).has(Metadata.of( "org.springframework.context.index.sample.jpa", "package-info")); } @@ -211,33 +211,33 @@ public class CandidateComponentsIndexerTests { // Validate nested type structure String nestedType = "org.springframework.context.index.sample.SampleEmbedded.Another$AnotherPublicCandidate"; Class type = ClassUtils.forName(nestedType, getClass().getClassLoader()); - assertThat(type, sameInstance(SampleEmbedded.Another.AnotherPublicCandidate.class)); + assertThat(type).isSameAs(SampleEmbedded.Another.AnotherPublicCandidate.class); CandidateComponentsMetadata metadata = compile(SampleEmbedded.class); - assertThat(metadata, hasComponent( + assertThat(metadata).has(Metadata.of( SampleEmbedded.PublicCandidate.class, Component.class)); - assertThat(metadata, hasComponent(nestedType, Component.class.getName())); - assertThat(metadata.getItems(), hasSize(2)); + assertThat(metadata).has(Metadata.of(nestedType, Component.class.getName())); + assertThat(metadata.getItems()).hasSize(2); } @Test public void embeddedNonStaticCandidateAreIgnored() { CandidateComponentsMetadata metadata = compile(SampleNonStaticEmbedded.class); - assertThat(metadata.getItems(), hasSize(0)); + assertThat(metadata.getItems()).hasSize(0); } private void testComponent(Class... classes) { CandidateComponentsMetadata metadata = compile(classes); for (Class c : classes) { - assertThat(metadata, hasComponent(c, Component.class)); + assertThat(metadata).has(Metadata.of(c, Component.class)); } - assertThat(metadata.getItems(), hasSize(classes.length)); + assertThat(metadata.getItems()).hasSize(classes.length); } private void testSingleComponent(Class target, Class... stereotypes) { CandidateComponentsMetadata metadata = compile(target); - assertThat(metadata, hasComponent(target, stereotypes)); - assertThat(metadata.getItems(), hasSize(1)); + assertThat(metadata).has(Metadata.of(target, stereotypes)); + assertThat(metadata.getItems()).hasSize(1); } private CandidateComponentsMetadata compile(Class... types) { diff --git a/spring-context-indexer/src/test/java/org/springframework/context/index/processor/Metadata.java b/spring-context-indexer/src/test/java/org/springframework/context/index/processor/Metadata.java index d330fdd435..30ca2caf1a 100644 --- a/spring-context-indexer/src/test/java/org/springframework/context/index/processor/Metadata.java +++ b/spring-context-indexer/src/test/java/org/springframework/context/index/processor/Metadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,84 +20,32 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; +import org.assertj.core.api.Condition; /** - * Hamcrest {@link org.hamcrest.Matcher Matcher} to help test {@link CandidateComponentsMetadata}. + * AssertJ {@link Condition} to help test {@link CandidateComponentsMetadata}. * * @author Stephane Nicoll */ -public class Metadata { +class Metadata { - public static ItemMetadataMatcher hasComponent(Class type, Class... stereotypes) { - return new ItemMetadataMatcher(type.getName(), stereotypes); + public static Condition of(Class type, Class... stereotypes) { + return of(type.getName(), Arrays.stream(stereotypes).map(Class::getName).collect(Collectors.toList())); } - public static ItemMetadataMatcher hasComponent(String type, String... stereotypes) { - return new ItemMetadataMatcher(type, stereotypes); + public static Condition of(String type, String... stereotypes) { + return of(type, Arrays.asList(stereotypes)); } - - private static class ItemMetadataMatcher extends BaseMatcher { - - private final String type; - - private final List stereotypes; - - private ItemMetadataMatcher(String type, List stereotypes) { - this.type = type; - this.stereotypes = stereotypes; - } - - public ItemMetadataMatcher(String type, String... stereotypes) { - this(type, Arrays.asList(stereotypes)); - } - - public ItemMetadataMatcher(String type, Class... stereotypes) { - this(type, Arrays.stream(stereotypes) - .map(Class::getName).collect(Collectors.toList())); - } - - @Override - public boolean matches(Object value) { - if (!(value instanceof CandidateComponentsMetadata)) { - return false; - } - ItemMetadata itemMetadata = getFirstItemWithType((CandidateComponentsMetadata) value, this.type); - if (itemMetadata == null) { - return false; - } - if (this.type != null && !this.type.equals(itemMetadata.getType())) { - return false; - } - if (this.stereotypes != null) { - for (String stereotype : this.stereotypes) { - if (!itemMetadata.getStereotypes().contains(stereotype)) { - return false; - } - } - if (this.stereotypes.size() != itemMetadata.getStereotypes().size()) { - return false; - } - } - return true; - } - - private ItemMetadata getFirstItemWithType(CandidateComponentsMetadata metadata, String type) { - for (ItemMetadata item : metadata.getItems()) { - if (item.getType().equals(type)) { - return item; - } - } - return null; - } - - @Override - public void describeTo(Description description) { - description.appendText("Candidates with type ").appendValue(this.type); - description.appendText(" and stereotypes ").appendValue(this.stereotypes); - } + public static Condition of(String type, + List stereotypes) { + return new Condition<>(metadata -> { + ItemMetadata itemMetadata = metadata.getItems().stream() + .filter(item -> item.getType().equals(type)) + .findFirst().orElse(null); + return itemMetadata != null && itemMetadata.getStereotypes().size() == stereotypes.size() + && itemMetadata.getStereotypes().containsAll(stereotypes); + }, "Candidates with type %s and stereotypes %s", type, stereotypes); } } diff --git a/spring-context-indexer/src/test/java/org/springframework/context/index/processor/PropertiesMarshallerTests.java b/spring-context-indexer/src/test/java/org/springframework/context/index/processor/PropertiesMarshallerTests.java index a40f9ce374..3116aecdb8 100644 --- a/spring-context-indexer/src/test/java/org/springframework/context/index/processor/PropertiesMarshallerTests.java +++ b/spring-context-indexer/src/test/java/org/springframework/context/index/processor/PropertiesMarshallerTests.java @@ -24,9 +24,9 @@ import java.util.HashSet; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.context.index.processor.Metadata.hasComponent; +import static org.assertj.core.api.Assertions.assertThat; + + /** * Tests for {@link PropertiesMarshaller}. @@ -45,9 +45,9 @@ public class PropertiesMarshallerTests { PropertiesMarshaller.write(metadata, outputStream); CandidateComponentsMetadata readMetadata = PropertiesMarshaller.read( new ByteArrayInputStream(outputStream.toByteArray())); - assertThat(readMetadata, hasComponent("com.foo", "first", "second")); - assertThat(readMetadata, hasComponent("com.bar", "first")); - assertThat(readMetadata.getItems(), hasSize(2)); + assertThat(readMetadata).has(Metadata.of("com.foo", "first", "second")); + assertThat(readMetadata).has(Metadata.of("com.bar", "first")); + assertThat(readMetadata.getItems()).hasSize(2); } private static ItemMetadata createItem(String type, String... stereotypes) { diff --git a/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java b/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java index 2bdaa0ee97..9df193ec34 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java @@ -23,10 +23,7 @@ import org.junit.rules.TestName; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -71,7 +68,7 @@ public abstract class AbstractTransactionSupportingCacheManagerTests { latch.await(); assertEquals(10, results.size()); - results.forEach(r -> assertThat(r, is(1))); // Only one method got invoked + results.forEach(r -> assertThat(r).isEqualTo(1)); // Only one method got invoked } protected String createRandomKey() { 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 92dd4e844f..12cc12bace 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 @@ -33,10 +33,8 @@ import org.springframework.cache.interceptor.CacheOperation; import org.springframework.cache.interceptor.CacheableOperation; import org.springframework.core.annotation.AliasFor; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -104,14 +102,14 @@ public class AnnotationCacheOperationSourceTests { Iterator it = ops.iterator(); CacheOperation cacheOperation = it.next(); - assertThat(cacheOperation, instanceOf(CacheableOperation.class)); - assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("directly declared"))); - assertThat(cacheOperation.getKey(), equalTo("")); + assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); + assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("directly declared")); + assertThat(cacheOperation.getKey()).isEqualTo(""); cacheOperation = it.next(); - assertThat(cacheOperation, instanceOf(CacheableOperation.class)); - assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("composedCache"))); - assertThat(cacheOperation.getKey(), equalTo("composedKey")); + assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); + assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("composedCache")); + assertThat(cacheOperation.getKey()).isEqualTo("composedKey"); } @Test @@ -120,24 +118,24 @@ public class AnnotationCacheOperationSourceTests { Iterator it = ops.iterator(); CacheOperation cacheOperation = it.next(); - assertThat(cacheOperation, instanceOf(CacheableOperation.class)); - assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("directly declared"))); - assertThat(cacheOperation.getKey(), equalTo("")); + assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); + assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("directly declared")); + assertThat(cacheOperation.getKey()).isEqualTo(""); cacheOperation = it.next(); - assertThat(cacheOperation, instanceOf(CacheableOperation.class)); - assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("composedCache"))); - assertThat(cacheOperation.getKey(), equalTo("composedKey")); + assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); + assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("composedCache")); + assertThat(cacheOperation.getKey()).isEqualTo("composedKey"); cacheOperation = it.next(); - assertThat(cacheOperation, instanceOf(CacheableOperation.class)); - assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("foo"))); - assertThat(cacheOperation.getKey(), equalTo("")); + assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); + assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("foo")); + assertThat(cacheOperation.getKey()).isEqualTo(""); cacheOperation = it.next(); - assertThat(cacheOperation, instanceOf(CacheEvictOperation.class)); - assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("composedCacheEvict"))); - assertThat(cacheOperation.getKey(), equalTo("composedEvictionKey")); + assertThat(cacheOperation).isInstanceOf(CacheEvictOperation.class); + assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("composedCacheEvict")); + assertThat(cacheOperation.getKey()).isEqualTo("composedEvictionKey"); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java b/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java index 2f26c1e4d6..7b6fb1723d 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java @@ -29,11 +29,9 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.context.ConfigurableApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; @@ -276,8 +274,8 @@ public abstract class AbstractCacheAnnotationTests { cache.clear(); service.unless(10); service.unless(11); - assertThat(cache.get(10).get(), equalTo(10L)); - assertThat(cache.get(11), nullValue()); + assertThat(cache.get(10).get()).isEqualTo(10L); + assertThat(cache.get(11)).isNull(); } public void testKeyExpression(CacheableService service) throws Exception { 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 dc22dc8adc..e8365bdd29 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java @@ -38,10 +38,6 @@ import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -105,21 +101,21 @@ public class ExpressionEvaluatorTests { public void withReturnValue() { EvaluationContext context = createEvaluationContext("theResult"); Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); - assertThat(value, equalTo("theResult")); + assertThat(value).isEqualTo("theResult"); } @Test public void withNullReturn() { EvaluationContext context = createEvaluationContext(null); Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); - assertThat(value, nullValue()); + assertThat(value).isNull(); } @Test public void withoutReturnValue() { EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT); Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); - assertThat(value, nullValue()); + assertThat(value).isNull(); } @Test @@ -139,7 +135,7 @@ public class ExpressionEvaluatorTests { EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT, applicationContext); Object value = new SpelExpressionParser().parseExpression("@myBean.class.getName()").getValue(context); - assertThat(value, is(String.class.getName())); + assertThat(value).isEqualTo(String.class.getName()); } private EvaluationContext createEvaluationContext(Object result) { diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/SimpleKeyGeneratorTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/SimpleKeyGeneratorTests.java index d071c8433f..6b64aae285 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/SimpleKeyGeneratorTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/SimpleKeyGeneratorTests.java @@ -18,10 +18,11 @@ package org.springframework.cache.interceptor; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; + + + + /** * Tests for {@link SimpleKeyGenerator} and {@link SimpleKey}. @@ -39,10 +40,10 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] {}); Object k2 = generateKey(new Object[] {}); Object k3 = generateKey(new Object[] { "different" }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); } @Test @@ -50,11 +51,11 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] { "a" }); Object k2 = generateKey(new Object[] { "a" }); Object k3 = generateKey(new Object[] { "different" }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); - assertThat(k1, equalTo("a")); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); + assertThat(k1).isEqualTo("a"); } @Test @@ -62,10 +63,10 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] { "a", 1, "b" }); Object k2 = generateKey(new Object[] { "a", 1, "b" }); Object k3 = generateKey(new Object[] { "b", 1, "a" }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); } @Test @@ -73,11 +74,11 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] { null }); Object k2 = generateKey(new Object[] { null }); Object k3 = generateKey(new Object[] { "different" }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); - assertThat(k1, instanceOf(SimpleKey.class)); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); + assertThat(k1).isInstanceOf(SimpleKey.class); } @Test @@ -85,10 +86,10 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] { "a", null, "b", null }); Object k2 = generateKey(new Object[] { "a", null, "b", null }); Object k3 = generateKey(new Object[] { "a", null, "b" }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); } @Test @@ -96,10 +97,10 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] { new String[]{"a", "b"} }); Object k2 = generateKey(new Object[] { new String[]{"a", "b"} }); Object k3 = generateKey(new Object[] { new String[]{"b", "a"} }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); } @Test @@ -107,10 +108,10 @@ public class SimpleKeyGeneratorTests { Object k1 = generateKey(new Object[] { new String[]{"a", "b"}, "c" }); Object k2 = generateKey(new Object[] { new String[]{"a", "b"}, "c" }); Object k3 = generateKey(new Object[] { new String[]{"b", "a"}, "c" }); - assertThat(k1.hashCode(), equalTo(k2.hashCode())); - assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); - assertThat(k1, equalTo(k2)); - assertThat(k1, not(equalTo(k3))); + assertThat(k1.hashCode()).isEqualTo(k2.hashCode()); + assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode()); + assertThat(k1).isEqualTo(k2); + assertThat(k1).isNotEqualTo(k3); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java index fdb1820341..93868d6236 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java @@ -34,11 +34,8 @@ import org.springframework.core.ResolvableType; import org.springframework.util.ObjectUtils; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -97,7 +94,7 @@ public class AnnotationConfigApplicationContextTests { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); TestBean testBean = context.getBean(TestBean.class); assertNotNull(testBean); - assertThat(testBean.name, equalTo("foo")); + assertThat(testBean.name).isEqualTo("foo"); } @Test @@ -114,19 +111,11 @@ public class AnnotationConfigApplicationContextTests { @Test public void getBeanByTypeAmbiguityRaisesException() { ApplicationContext context = new AnnotationConfigApplicationContext(TwoTestBeanConfig.class); - - try { - context.getBean(TestBean.class); - } - catch (NoSuchBeanDefinitionException ex) { - assertThat(ex.getMessage(), - allOf( - containsString("No qualifying bean of type '" + TestBean.class.getName() + "'"), - containsString("tb1"), - containsString("tb2") - ) - ); - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + context.getBean(TestBean.class)) + .withMessageContaining("No qualifying bean of type '" + TestBean.class.getName() + "'") + .withMessageContaining("tb1") + .withMessageContaining("tb2"); } /** @@ -158,7 +147,7 @@ public class AnnotationConfigApplicationContextTests { @Test public void autowiringIsEnabledByDefault() { ApplicationContext context = new AnnotationConfigApplicationContext(AutowiredConfig.class); - assertThat(context.getBean(TestBean.class).name, equalTo("foo")); + assertThat(context.getBean(TestBean.class).name).isEqualTo("foo"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodMetadataTests.java b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodMetadataTests.java index 810e521704..711b4ebf11 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodMetadataTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodMetadataTests.java @@ -25,9 +25,10 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; + + + /** * @author Phillip Webb @@ -39,10 +40,10 @@ public class BeanMethodMetadataTests { public void providesBeanMethodBeanDefinition() throws Exception { AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(Conf.class); BeanDefinition beanDefinition = context.getBeanDefinition("myBean"); - assertThat("should provide AnnotatedBeanDefinition", beanDefinition, instanceOf(AnnotatedBeanDefinition.class)); + assertThat(beanDefinition).as("should provide AnnotatedBeanDefinition").isInstanceOf(AnnotatedBeanDefinition.class); Map annotationAttributes = ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata().getAnnotationAttributes(MyAnnotation.class.getName()); - assertThat(annotationAttributes.get("value"), equalTo("test")); + assertThat(annotationAttributes.get("value")).isEqualTo("test"); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java index bc71f4f2db..f863860a6b 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java @@ -25,8 +25,7 @@ import org.springframework.aop.interceptor.SimpleTraceInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.factory.support.RootBeanDefinition; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -98,7 +97,7 @@ public class BeanMethodPolymorphismTests { ctx.register(ConfigWithOverloading.class); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertThat(ctx.getBean(String.class), equalTo("regular")); + assertThat(ctx.getBean(String.class)).isEqualTo("regular"); } @Test @@ -108,7 +107,7 @@ public class BeanMethodPolymorphismTests { ctx.getDefaultListableBeanFactory().registerSingleton("anInt", 5); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertThat(ctx.getBean(String.class), equalTo("overloaded5")); + assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); } @Test @@ -118,7 +117,7 @@ public class BeanMethodPolymorphismTests { ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); - assertThat(ctx.getBean(String.class), equalTo("regular")); + assertThat(ctx.getBean(String.class)).isEqualTo("regular"); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); } @@ -130,7 +129,7 @@ public class BeanMethodPolymorphismTests { ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); - assertThat(ctx.getBean(String.class), equalTo("overloaded5")); + assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); } @@ -141,7 +140,7 @@ public class BeanMethodPolymorphismTests { ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); - assertThat(ctx.getBean(String.class), equalTo("overloaded5")); + assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); } @@ -153,7 +152,7 @@ public class BeanMethodPolymorphismTests { ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); - assertThat(ctx.getBean(String.class), equalTo("overloaded5")); + assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); } @@ -165,7 +164,7 @@ public class BeanMethodPolymorphismTests { @Test public void beanMethodShadowing() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ShadowConfig.class); - assertThat(ctx.getBean(String.class), equalTo("shadow")); + assertThat(ctx.getBean(String.class)).isEqualTo("shadow"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java index 2e7d2958da..e23f392da3 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java @@ -55,9 +55,7 @@ import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -368,7 +366,7 @@ public class ClassPathScanningCandidateComponentProviderTests { public void testWithNullEnvironment() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); Set candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE); - assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(false)); + assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class)).isFalse(); } @Test @@ -378,7 +376,7 @@ public class ClassPathScanningCandidateComponentProviderTests { env.setActiveProfiles("other"); provider.setEnvironment(env); Set candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE); - assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(false)); + assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class)).isFalse(); } @Test @@ -388,7 +386,7 @@ public class ClassPathScanningCandidateComponentProviderTests { env.setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); provider.setEnvironment(env); Set candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE); - assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(true)); + assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class)).isTrue(); } @Test @@ -396,7 +394,7 @@ public class ClassPathScanningCandidateComponentProviderTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ProfileAnnotatedComponent.class); ctx.refresh(); - assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false)); + assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isFalse(); } @Test @@ -405,7 +403,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); ctx.register(ProfileAnnotatedComponent.class); ctx.refresh(); - assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true)); + assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isTrue(); } @Test @@ -414,7 +412,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles(DevComponent.PROFILE_NAME); ctx.register(ProfileMetaAnnotatedComponent.class); ctx.refresh(); - assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME), is(true)); + assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME)).isTrue(); } @Test @@ -423,7 +421,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles("other"); ctx.register(ProfileAnnotatedComponent.class); ctx.refresh(); - assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false)); + assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isFalse(); } @Test @@ -432,7 +430,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles("other"); ctx.register(ProfileMetaAnnotatedComponent.class); ctx.refresh(); - assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME), is(false)); + assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME)).isFalse(); } @Test @@ -442,7 +440,7 @@ public class ClassPathScanningCandidateComponentProviderTests { // no active profiles are set ctx.register(DefaultProfileAnnotatedComponent.class); ctx.refresh(); - assertThat(ctx.containsBean(DefaultProfileAnnotatedComponent.BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DefaultProfileAnnotatedComponent.BEAN_NAME)).isTrue(); } @Test @@ -455,7 +453,7 @@ public class ClassPathScanningCandidateComponentProviderTests { // no active profiles are set ctx.register(beanClass); ctx.refresh(); - assertThat(ctx.containsBean(beanName), is(true)); + assertThat(ctx.containsBean(beanName)).isTrue(); } { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -463,7 +461,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles("dev"); ctx.register(beanClass); ctx.refresh(); - assertThat(ctx.containsBean(beanName), is(true)); + assertThat(ctx.containsBean(beanName)).isTrue(); } { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -471,7 +469,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles("other"); ctx.register(beanClass); ctx.refresh(); - assertThat(ctx.containsBean(beanName), is(false)); + assertThat(ctx.containsBean(beanName)).isFalse(); } } @@ -485,7 +483,7 @@ public class ClassPathScanningCandidateComponentProviderTests { // no active profiles are set ctx.register(beanClass); ctx.refresh(); - assertThat(ctx.containsBean(beanName), is(true)); + assertThat(ctx.containsBean(beanName)).isTrue(); } { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -493,7 +491,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles("dev"); ctx.register(beanClass); ctx.refresh(); - assertThat(ctx.containsBean(beanName), is(true)); + assertThat(ctx.containsBean(beanName)).isTrue(); } { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -501,7 +499,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ctx.getEnvironment().setActiveProfiles("other"); ctx.register(beanClass); ctx.refresh(); - assertThat(ctx.containsBean(beanName), is(false)); + assertThat(ctx.containsBean(beanName)).isFalse(); } } @@ -517,7 +515,7 @@ public class ClassPathScanningCandidateComponentProviderTests { private void assertBeanDefinitionType(Set candidates, Class expectedType) { candidates.forEach(c -> - assertThat(c, is(instanceOf(expectedType))) + assertThat(c).isInstanceOf(expectedType) ); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java index 9b200d99c9..b1488544ed 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java @@ -61,12 +61,7 @@ import org.springframework.core.type.filter.TypeFilter; import org.springframework.tests.context.SimpleMapScope; import org.springframework.util.SerializationTestUtils; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -88,8 +83,8 @@ public class ComponentScanAnnotationIntegrationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan(example.scannable._package.class.getPackage().getName()); ctx.refresh(); - assertThat("control scan for example.scannable package failed to register FooServiceImpl bean", - ctx.containsBean("fooServiceImpl"), is(true)); + assertThat(ctx.containsBean("fooServiceImpl")).as( + "control scan for example.scannable package failed to register FooServiceImpl bean").isTrue(); } @Test @@ -99,10 +94,11 @@ public class ComponentScanAnnotationIntegrationTests { ctx.refresh(); ctx.getBean(ComponentScanAnnotatedConfig.class); ctx.getBean(TestBean.class); - assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig"), is(true)); - assertThat("@ComponentScan annotated @Configuration class registered directly against " + - "AnnotationConfigApplicationContext did not trigger component scanning as expected", - ctx.containsBean("fooServiceImpl"), is(true)); + assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfig")).as("config class bean not found") + .isTrue(); + assertThat(ctx.containsBean("fooServiceImpl")).as("@ComponentScan annotated @Configuration class registered directly against " + + "AnnotationConfigApplicationContext did not trigger component scanning as expected") + .isTrue(); } @Test @@ -112,10 +108,11 @@ public class ComponentScanAnnotationIntegrationTests { ctx.refresh(); ctx.getBean(ComponentScanAnnotatedConfig_WithValueAttribute.class); ctx.getBean(TestBean.class); - assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig_WithValueAttribute"), is(true)); - assertThat("@ComponentScan annotated @Configuration class registered directly against " + - "AnnotationConfigApplicationContext did not trigger component scanning as expected", - ctx.containsBean("fooServiceImpl"), is(true)); + assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfig_WithValueAttribute")).as("config class bean not found") + .isTrue(); + assertThat(ctx.containsBean("fooServiceImpl")).as("@ComponentScan annotated @Configuration class registered directly against " + + "AnnotationConfigApplicationContext did not trigger component scanning as expected") + .isTrue(); } @Test @@ -124,11 +121,13 @@ public class ComponentScanAnnotationIntegrationTests { ctx.register(ComponentScanAnnotatedConfigWithImplicitBasePackage.class); ctx.refresh(); ctx.getBean(ComponentScanAnnotatedConfigWithImplicitBasePackage.class); - assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfigWithImplicitBasePackage"), is(true)); - assertThat("@ComponentScan annotated @Configuration class registered directly against " + - "AnnotationConfigApplicationContext did not trigger component scanning as expected", - ctx.containsBean("scannedComponent"), is(true)); - assertThat("@Bean method overrides scanned class", ctx.getBean(ConfigurableComponent.class).isFlag(), is(true)); + assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfigWithImplicitBasePackage")).as("config class bean not found") + .isTrue(); + assertThat(ctx.containsBean("scannedComponent")).as("@ComponentScan annotated @Configuration class registered directly against " + + "AnnotationConfigApplicationContext did not trigger component scanning as expected") + .isTrue(); + assertThat(ctx.getBean(ConfigurableComponent.class).isFlag()).as("@Bean method overrides scanned class") + .isTrue(); } @Test @@ -140,11 +139,11 @@ public class ComponentScanAnnotationIntegrationTests { ctx.getBean(SimpleComponent.class); ctx.getBean(ClassWithNestedComponents.NestedComponent.class); ctx.getBean(ClassWithNestedComponents.OtherNestedComponent.class); - assertThat("config class bean not found", - ctx.containsBeanDefinition("componentScanAnnotationIntegrationTests.ComposedAnnotationConfig"), is(true)); - assertThat("@ComponentScan annotated @Configuration class registered directly against " + - "AnnotationConfigApplicationContext did not trigger component scanning as expected", - ctx.containsBean("simpleComponent"), is(true)); + assertThat(ctx.containsBeanDefinition("componentScanAnnotationIntegrationTests.ComposedAnnotationConfig")).as("config class bean not found") + .isTrue(); + assertThat(ctx.containsBean("simpleComponent")).as("@ComponentScan annotated @Configuration class registered directly against " + + "AnnotationConfigApplicationContext did not trigger component scanning as expected") + .isTrue(); } @Test @@ -158,10 +157,11 @@ public class ComponentScanAnnotationIntegrationTests { ctx.refresh(); ctx.getBean(ComponentScanAnnotatedConfig.class); ctx.getBean(TestBean.class); - assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig"), is(true)); - assertThat("@ComponentScan annotated @Configuration class registered " + - "as bean definition did not trigger component scanning as expected", - ctx.containsBean("fooServiceImpl"), is(true)); + assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfig")).as("config class bean not found") + .isTrue(); + assertThat(ctx.containsBean("fooServiceImpl")).as("@ComponentScan annotated @Configuration class registered as bean " + + "definition did not trigger component scanning as expected") + .isTrue(); } @Test @@ -169,8 +169,8 @@ public class ComponentScanAnnotationIntegrationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ComponentScanWithBeanNameGenerator.class); ctx.refresh(); - assertThat(ctx.containsBean("custom_fooServiceImpl"), is(true)); - assertThat(ctx.containsBean("fooServiceImpl"), is(false)); + assertThat(ctx.containsBean("custom_fooServiceImpl")).isTrue(); + assertThat(ctx.containsBean("fooServiceImpl")).isFalse(); } @Test @@ -178,15 +178,15 @@ public class ComponentScanAnnotationIntegrationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithScopeResolver.class); // custom scope annotation makes the bean prototype scoped. subsequent calls // to getBean should return distinct instances. - assertThat(ctx.getBean(CustomScopeAnnotationBean.class), not(sameInstance(ctx.getBean(CustomScopeAnnotationBean.class)))); - assertThat(ctx.containsBean("scannedComponent"), is(false)); + assertThat(ctx.getBean(CustomScopeAnnotationBean.class)).isNotSameAs(ctx.getBean(CustomScopeAnnotationBean.class)); + assertThat(ctx.containsBean("scannedComponent")).isFalse(); } @Test public void multiComponentScan() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MultiComponentScan.class); - assertThat(ctx.getBean(CustomScopeAnnotationBean.class), not(sameInstance(ctx.getBean(CustomScopeAnnotationBean.class)))); - assertThat(ctx.containsBean("scannedComponent"), is(true)); + assertThat(ctx.getBean(CustomScopeAnnotationBean.class)).isNotSameAs(ctx.getBean(CustomScopeAnnotationBean.class)); + assertThat(ctx.containsBean("scannedComponent")).isTrue(); } @Test @@ -194,7 +194,7 @@ public class ComponentScanAnnotationIntegrationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithCustomTypeFilter.class); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("componentScanParserTests.KustomAnnotationAutowiredBean")); KustomAnnotationAutowiredBean testBean = ctx.getBean("componentScanParserTests.KustomAnnotationAutowiredBean", KustomAnnotationAutowiredBean.class); - assertThat(testBean.getDependency(), notNullValue()); + assertThat(testBean.getDependency()).isNotNull(); } @Test @@ -212,12 +212,12 @@ public class ComponentScanAnnotationIntegrationTests { // should cast to the interface FooService bean = (FooService) ctx.getBean("scopedProxyTestBean"); // should be dynamic proxy - assertThat(AopUtils.isJdkDynamicProxy(bean), is(true)); + assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); // test serializability - assertThat(bean.foo(1), equalTo("bar")); + assertThat(bean.foo(1)).isEqualTo("bar"); FooService deserialized = (FooService) SerializationTestUtils.serializeAndDeserialize(bean); - assertThat(deserialized, notNullValue()); - assertThat(deserialized.foo(1), equalTo("bar")); + assertThat(deserialized).isNotNull(); + assertThat(deserialized.foo(1)).isEqualTo("bar"); } @Test @@ -229,7 +229,7 @@ public class ComponentScanAnnotationIntegrationTests { // should cast to the interface FooService bean = (FooService) ctx.getBean("scopedProxyTestBean"); // should be dynamic proxy - assertThat(AopUtils.isJdkDynamicProxy(bean), is(true)); + assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); } @Test @@ -241,7 +241,7 @@ public class ComponentScanAnnotationIntegrationTests { // should cast to the interface FooService bean = (FooService) ctx.getBean("scopedProxyTestBean"); // should be dynamic proxy - assertThat(AopUtils.isJdkDynamicProxy(bean), is(true)); + assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); } @Test @@ -267,7 +267,7 @@ public class ComponentScanAnnotationIntegrationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ComponentScanWithBasePackagesAndValueAlias.class); ctx.refresh(); - assertThat(ctx.containsBean("fooServiceImpl"), is(true)); + assertThat(ctx.containsBean("fooServiceImpl")).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationRecursionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationRecursionTests.java index f525de0007..840c9b4ed8 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationRecursionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationRecursionTests.java @@ -23,8 +23,8 @@ import org.springframework.context.annotation.componentscan.level1.Level1Config; import org.springframework.context.annotation.componentscan.level2.Level2Config; import org.springframework.context.annotation.componentscan.level3.Level3Component; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests ensuring that configuration classes marked with @ComponentScan @@ -47,8 +47,8 @@ public class ComponentScanAnnotationRecursionTests { ctx.getBean(Level3Component.class); // assert that enhancement is working - assertThat(ctx.getBean("level1Bean"), sameInstance(ctx.getBean("level1Bean"))); - assertThat(ctx.getBean("level2Bean"), sameInstance(ctx.getBean("level2Bean"))); + assertThat(ctx.getBean("level1Bean")).isSameAs(ctx.getBean("level1Bean")); + assertThat(ctx.getBean("level2Bean")).isSameAs(ctx.getBean("level2Bean")); } public void evenCircularScansAreSupported() { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java index dd0703e1e8..6c7305d1be 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java @@ -33,8 +33,7 @@ import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.TypeFilter; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -127,7 +126,7 @@ public class ComponentScanParserTests { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load(xmlLocation); context.refresh(); - assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false)); + assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isFalse(); context.close(); } { // should include the profile-annotated bean with active profiles set @@ -135,7 +134,7 @@ public class ComponentScanParserTests { context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); context.load(xmlLocation); context.refresh(); - assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true)); + assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isTrue(); context.close(); } { // ensure the same works for AbstractRefreshableApplicationContext impls too @@ -143,7 +142,7 @@ public class ComponentScanParserTests { false); context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); context.refresh(); - assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true)); + assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isTrue(); context.close(); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java index c89d578583..d6b66b4f4a 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java @@ -24,11 +24,8 @@ import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests semantics of declaring {@link BeanFactoryPostProcessor}-returning @Bean @@ -47,7 +44,7 @@ public class ConfigurationClassAndBFPPTests { ctx.refresh(); // instance method BFPP interferes with lifecycle -> autowiring fails! // WARN-level logging should have been issued about returning BFPP from non-static @Bean method - assertThat(ctx.getBean(AutowiredConfigWithBFPPAsInstanceMethod.class).autowiredTestBean, nullValue()); + assertThat(ctx.getBean(AutowiredConfigWithBFPPAsInstanceMethod.class).autowiredTestBean).isNull(); } @Test @@ -56,7 +53,7 @@ public class ConfigurationClassAndBFPPTests { ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsStaticMethod.class); ctx.refresh(); // static method BFPP does not interfere with lifecycle -> autowiring succeeds - assertThat(ctx.getBean(AutowiredConfigWithBFPPAsStaticMethod.class).autowiredTestBean, notNullValue()); + assertThat(ctx.getBean(AutowiredConfigWithBFPPAsStaticMethod.class).autowiredTestBean).isNotNull(); } @@ -106,7 +103,7 @@ public class ConfigurationClassAndBFPPTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithStaticBeanMethod.class); ctx.refresh(); - assertThat(ConfigWithStaticBeanMethod.testBean(), not(sameInstance(ConfigWithStaticBeanMethod.testBean()))); + assertThat(ConfigWithStaticBeanMethod.testBean()).isNotSameAs(ConfigWithStaticBeanMethod.testBean()); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java index c91b6eae8a..e8c21919bb 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java @@ -23,8 +23,8 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests cornering the issue reported in SPR-8080. If the product of a @Bean method @@ -56,7 +56,7 @@ public class ConfigurationClassPostConstructAndAutowiringTests { assertions(ctx); Config2 config2 = ctx.getBean(Config2.class); - assertThat(config2.testBean, is(ctx.getBean(TestBean.class))); + assertThat(config2.testBean).isEqualTo(ctx.getBean(TestBean.class)); } /** @@ -75,8 +75,8 @@ public class ConfigurationClassPostConstructAndAutowiringTests { private void assertions(AnnotationConfigApplicationContext ctx) { Config1 config1 = ctx.getBean(Config1.class); TestBean testBean = ctx.getBean(TestBean.class); - assertThat(config1.beanMethodCallCount, is(1)); - assertThat(testBean.getAge(), is(2)); + assertThat(config1.beanMethodCallCount).isEqualTo(1); + assertThat(testBean.getAge()).isEqualTo(2); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java index 6cbd3dd7a5..255d72ab3f 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java @@ -31,8 +31,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.core.type.AnnotationMetadata; import org.springframework.stereotype.Component; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -248,7 +247,7 @@ public class ConfigurationClassWithConditionTests { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(MetaConditional.class.getName())); - assertThat(attributes.getString("value"), equalTo("test")); + assertThat(attributes.getString("value")).isEqualTo("test"); return true; } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java index 8cd1d630c5..6b07052641 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java @@ -24,8 +24,8 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Chris Beams @@ -48,27 +48,27 @@ public class DestroyMethodInferenceTests { WithInheritedCloseMethod c8 = ctx.getBean("c8", WithInheritedCloseMethod.class); WithDisposableBean c9 = ctx.getBean("c9", WithDisposableBean.class); - assertThat(c0.closed, is(false)); - assertThat(c1.closed, is(false)); - assertThat(c2.closed, is(false)); - assertThat(c3.closed, is(false)); - assertThat(c4.closed, is(false)); - assertThat(c5.closed, is(false)); - assertThat(c6.closed, is(false)); - assertThat(c7.closed, is(false)); - assertThat(c8.closed, is(false)); - assertThat(c9.closed, is(false)); + assertThat(c0.closed).as("c0").isFalse(); + assertThat(c1.closed).as("c1").isFalse(); + assertThat(c2.closed).as("c2").isFalse(); + assertThat(c3.closed).as("c3").isFalse(); + assertThat(c4.closed).as("c4").isFalse(); + assertThat(c5.closed).as("c5").isFalse(); + assertThat(c6.closed).as("c6").isFalse(); + assertThat(c7.closed).as("c7").isFalse(); + assertThat(c8.closed).as("c8").isFalse(); + assertThat(c9.closed).as("c9").isFalse(); ctx.close(); - assertThat("c0", c0.closed, is(true)); - assertThat("c1", c1.closed, is(true)); - assertThat("c2", c2.closed, is(true)); - assertThat("c3", c3.closed, is(true)); - assertThat("c4", c4.closed, is(true)); - assertThat("c5", c5.closed, is(true)); - assertThat("c6", c6.closed, is(false)); - assertThat("c7", c7.closed, is(true)); - assertThat("c8", c8.closed, is(false)); - assertThat("c9", c9.closed, is(true)); + assertThat(c0.closed).as("c0").isTrue(); + assertThat(c1.closed).as("c1").isTrue(); + assertThat(c2.closed).as("c2").isTrue(); + assertThat(c3.closed).as("c3").isTrue(); + assertThat(c4.closed).as("c4").isTrue(); + assertThat(c5.closed).as("c5").isTrue(); + assertThat(c6.closed).as("c6").isFalse(); + assertThat(c7.closed).as("c7").isTrue(); + assertThat(c8.closed).as("c8").isFalse(); + assertThat(c9.closed).as("c9").isTrue(); } @Test @@ -81,16 +81,16 @@ public class DestroyMethodInferenceTests { WithNoCloseMethod x4 = ctx.getBean("x4", WithNoCloseMethod.class); WithInheritedCloseMethod x8 = ctx.getBean("x8", WithInheritedCloseMethod.class); - assertThat(x1.closed, is(false)); - assertThat(x2.closed, is(false)); - assertThat(x3.closed, is(false)); - assertThat(x4.closed, is(false)); + assertThat(x1.closed).isFalse(); + assertThat(x2.closed).isFalse(); + assertThat(x3.closed).isFalse(); + assertThat(x4.closed).isFalse(); ctx.close(); - assertThat(x1.closed, is(false)); - assertThat(x2.closed, is(true)); - assertThat(x3.closed, is(true)); - assertThat(x4.closed, is(false)); - assertThat(x8.closed, is(false)); + assertThat(x1.closed).isFalse(); + assertThat(x2.closed).isTrue(); + assertThat(x3.closed).isTrue(); + assertThat(x4.closed).isFalse(); + assertThat(x8.closed).isFalse(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java b/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java index 17c9cd4857..1a3d66fdec 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java @@ -32,8 +32,7 @@ import org.springframework.aop.support.AopUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -49,7 +48,7 @@ public class EnableAspectJAutoProxyTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithJdkProxy.class); aspectIsApplied(ctx); - assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class)), is(true)); + assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class))).isTrue(); } @Test @@ -57,7 +56,7 @@ public class EnableAspectJAutoProxyTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithCglibProxy.class); aspectIsApplied(ctx); - assertThat(AopUtils.isCglibProxy(ctx.getBean(FooService.class)), is(true)); + assertThat(AopUtils.isCglibProxy(ctx.getBean(FooService.class))).isTrue(); } @Test @@ -65,7 +64,7 @@ public class EnableAspectJAutoProxyTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithExposedProxy.class); aspectIsApplied(ctx); - assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class)), is(true)); + assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class))).isTrue(); } private void aspectIsApplied(ApplicationContext ctx) { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java index 3e51bf113d..85ddbdae01 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java @@ -36,9 +36,7 @@ import org.springframework.core.type.StandardAnnotationMetadata; import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor; import org.springframework.util.Assert; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -61,11 +59,11 @@ public class ImportAwareTests { ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class); AnnotationMetadata importMetadata = importAwareConfig.importMetadata; - assertThat("import metadata was not injected", importMetadata, notNullValue()); - assertThat(importMetadata.getClassName(), is(ImportingConfig.class.getName())); + assertThat(importMetadata).isNotNull(); + assertThat(importMetadata.getClassName()).isEqualTo(ImportingConfig.class.getName()); AnnotationAttributes importAttribs = AnnotationConfigUtils.attributesFor(importMetadata, Import.class); Class[] importedClasses = importAttribs.getClassArray("value"); - assertThat(importedClasses[0].getName(), is(ImportedConfig.class.getName())); + assertThat(importedClasses[0].getName()).isEqualTo(ImportedConfig.class.getName()); } @Test @@ -77,11 +75,11 @@ public class ImportAwareTests { ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class); AnnotationMetadata importMetadata = importAwareConfig.importMetadata; - assertThat("import metadata was not injected", importMetadata, notNullValue()); - assertThat(importMetadata.getClassName(), is(IndirectlyImportingConfig.class.getName())); + assertThat(importMetadata).isNotNull(); + assertThat(importMetadata.getClassName()).isEqualTo(IndirectlyImportingConfig.class.getName()); AnnotationAttributes enableAttribs = AnnotationConfigUtils.attributesFor(importMetadata, EnableImportedConfig.class); String foo = enableAttribs.getString("foo"); - assertThat(foo, is("xyz")); + assertThat(foo).isEqualTo("xyz"); } @Test @@ -93,11 +91,11 @@ public class ImportAwareTests { ImportedConfigLite importAwareConfig = ctx.getBean(ImportedConfigLite.class); AnnotationMetadata importMetadata = importAwareConfig.importMetadata; - assertThat("import metadata was not injected", importMetadata, notNullValue()); - assertThat(importMetadata.getClassName(), is(ImportingConfigLite.class.getName())); + assertThat(importMetadata).isNotNull(); + assertThat(importMetadata.getClassName()).isEqualTo(ImportingConfigLite.class.getName()); AnnotationAttributes importAttribs = AnnotationConfigUtils.attributesFor(importMetadata, Import.class); Class[] importedClasses = importAttribs.getClassArray("value"); - assertThat(importedClasses[0].getName(), is(ImportedConfigLite.class.getName())); + assertThat(importedClasses[0].getName()).isEqualTo(ImportedConfigLite.class.getName()); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrarTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrarTests.java index f7a9a804ed..0d2503ce94 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrarTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrarTests.java @@ -35,9 +35,8 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Integration tests for {@link ImportBeanDefinitionRegistrar}. @@ -52,10 +51,10 @@ public class ImportBeanDefinitionRegistrarTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); context.getBean(MessageSource.class); - assertThat(SampleRegistrar.beanFactory, is(context.getBeanFactory())); - assertThat(SampleRegistrar.classLoader, is(context.getBeanFactory().getBeanClassLoader())); - assertThat(SampleRegistrar.resourceLoader, is(notNullValue())); - assertThat(SampleRegistrar.environment, is(context.getEnvironment())); + assertThat(SampleRegistrar.beanFactory).isEqualTo(context.getBeanFactory()); + assertThat(SampleRegistrar.classLoader).isEqualTo(context.getBeanFactory().getBeanClassLoader()); + assertThat(SampleRegistrar.resourceLoader).isNotNull(); + assertThat(SampleRegistrar.environment).isEqualTo(context.getEnvironment()); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java index 376e473e43..036600683e 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java @@ -31,8 +31,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -import org.hamcrest.Matcher; -import org.hamcrest.collection.IsIterableContainingInOrder; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; @@ -53,11 +51,7 @@ import org.springframework.lang.Nullable; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; @@ -100,20 +94,20 @@ public class ImportSelectorTests { @Test public void invokeAwareMethodsInImportSelector() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class); - assertThat(SampleImportSelector.beanFactory, is(context.getBeanFactory())); - assertThat(SampleImportSelector.classLoader, is(context.getBeanFactory().getBeanClassLoader())); - assertThat(SampleImportSelector.resourceLoader, is(notNullValue())); - assertThat(SampleImportSelector.environment, is(context.getEnvironment())); + assertThat(SampleImportSelector.beanFactory).isEqualTo(context.getBeanFactory()); + assertThat(SampleImportSelector.classLoader).isEqualTo(context.getBeanFactory().getBeanClassLoader()); + assertThat(SampleImportSelector.resourceLoader).isNotNull(); + assertThat(SampleImportSelector.environment).isEqualTo(context.getEnvironment()); } @Test public void correctMetaDataOnIndirectImports() { new AnnotationConfigApplicationContext(IndirectConfig.class); - Matcher isFromIndirect = equalTo(IndirectImport.class.getName()); - assertThat(importFrom.get(ImportSelector1.class), isFromIndirect); - assertThat(importFrom.get(ImportSelector2.class), isFromIndirect); - assertThat(importFrom.get(DeferredImportSelector1.class), isFromIndirect); - assertThat(importFrom.get(DeferredImportSelector2.class), isFromIndirect); + String indirectImport = IndirectImport.class.getName(); + assertThat(importFrom.get(ImportSelector1.class)).isEqualTo(indirectImport); + assertThat(importFrom.get(ImportSelector2.class)).isEqualTo(indirectImport); + assertThat(importFrom.get(DeferredImportSelector1.class)).isEqualTo(indirectImport); + assertThat(importFrom.get(DeferredImportSelector2.class)).isEqualTo(indirectImport); } @Test @@ -127,9 +121,9 @@ public class ImportSelectorTests { ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any()); - assertThat(TestImportGroup.instancesCount.get(), equalTo(1)); - assertThat(TestImportGroup.imports.size(), equalTo(1)); - assertThat(TestImportGroup.imports.values().iterator().next().size(), equalTo(2)); + assertThat(TestImportGroup.instancesCount.get()).isEqualTo(1); + assertThat(TestImportGroup.imports.size()).isEqualTo(1); + assertThat(TestImportGroup.imports.values().iterator().next().size()).isEqualTo(2); } @Test @@ -142,11 +136,11 @@ public class ImportSelectorTests { InOrder ordered = inOrder(beanFactory); ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any()); - assertThat(TestImportGroup.instancesCount.get(), equalTo(1)); - assertThat(TestImportGroup.imports.size(), equalTo(2)); + assertThat(TestImportGroup.instancesCount.get()).isEqualTo(1); + assertThat(TestImportGroup.imports.size()).isEqualTo(2); Iterator iterator = TestImportGroup.imports.keySet().iterator(); - assertThat(iterator.next().getClassName(), equalTo(GroupedConfig2.class.getName())); - assertThat(iterator.next().getClassName(), equalTo(GroupedConfig1.class.getName())); + assertThat(iterator.next().getClassName()).isEqualTo(GroupedConfig2.class.getName()); + assertThat(iterator.next().getClassName()).isEqualTo(GroupedConfig1.class.getName()); } @Test @@ -159,15 +153,14 @@ public class ImportSelectorTests { ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("e"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any()); - assertThat(TestImportGroup.instancesCount.get(), equalTo(2)); - assertThat(TestImportGroup.imports.size(), equalTo(2)); - assertThat(TestImportGroup.allImports(), hasEntry( - is(ParentConfiguration1.class.getName()), - IsIterableContainingInOrder.contains(DeferredImportSelector1.class.getName(), - ChildConfiguration1.class.getName()))); - assertThat(TestImportGroup.allImports(), hasEntry( - is(ChildConfiguration1.class.getName()), - IsIterableContainingInOrder.contains(DeferredImportedSelector3.class.getName()))); + assertThat(TestImportGroup.instancesCount.get()).isEqualTo(2); + assertThat(TestImportGroup.imports.size()).isEqualTo(2); + assertThat(TestImportGroup.allImports()) + .containsOnlyKeys(ParentConfiguration1.class.getName(), ChildConfiguration1.class.getName()); + assertThat(TestImportGroup.allImports().get(ParentConfiguration1.class.getName())) + .containsExactly(DeferredImportSelector1.class.getName(), ChildConfiguration1.class.getName()); + assertThat(TestImportGroup.allImports().get(ChildConfiguration1.class.getName())) + .containsExactly(DeferredImportedSelector3.class.getName()); } @Test @@ -179,24 +172,23 @@ public class ImportSelectorTests { InOrder ordered = inOrder(beanFactory); ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any()); - assertThat(TestImportGroup.instancesCount.get(), equalTo(2)); - assertThat(TestImportGroup.allImports().size(), equalTo(2)); - assertThat(TestImportGroup.allImports(), hasEntry( - is(ParentConfiguration2.class.getName()), - IsIterableContainingInOrder.contains(DeferredImportSelector2.class.getName(), - ChildConfiguration2.class.getName()))); - assertThat(TestImportGroup.allImports(), hasEntry( - is(ChildConfiguration2.class.getName()), - IsIterableContainingInOrder.contains(DeferredImportSelector2.class.getName()))); + assertThat(TestImportGroup.instancesCount.get()).isEqualTo(2); + assertThat(TestImportGroup.allImports().size()).isEqualTo(2); + assertThat(TestImportGroup.allImports()) + .containsOnlyKeys(ParentConfiguration2.class.getName(), ChildConfiguration2.class.getName()); + assertThat(TestImportGroup.allImports().get(ParentConfiguration2.class.getName())) + .containsExactly(DeferredImportSelector2.class.getName(), ChildConfiguration2.class.getName()); + assertThat(TestImportGroup.allImports().get(ChildConfiguration2.class.getName())) + .containsExactly(DeferredImportSelector2.class.getName()); } @Test public void invokeAwareMethodsInImportGroup() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GroupedConfig1.class); - assertThat(TestImportGroup.beanFactory, is(context.getBeanFactory())); - assertThat(TestImportGroup.classLoader, is(context.getBeanFactory().getBeanClassLoader())); - assertThat(TestImportGroup.resourceLoader, is(notNullValue())); - assertThat(TestImportGroup.environment, is(context.getEnvironment())); + assertThat(TestImportGroup.beanFactory).isEqualTo(context.getBeanFactory()); + assertThat(TestImportGroup.classLoader).isEqualTo(context.getBeanFactory().getBeanClassLoader()); + assertThat(TestImportGroup.resourceLoader).isNotNull(); + assertThat(TestImportGroup.environment).isEqualTo(context.getEnvironment()); } 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 49fc82ba52..105227a557 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 @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.stereotype.Component; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; @@ -52,7 +51,7 @@ public class NestedConfigurationClassTests { ctx.getBean("l2Bean"); // ensure that override order is correct - assertThat(ctx.getBean("overrideBean", TestBean.class).getName(), is("override-l1")); + assertThat(ctx.getBean("overrideBean", TestBean.class).getName()).isEqualTo("override-l1"); } @Test @@ -74,7 +73,7 @@ public class NestedConfigurationClassTests { ctx.getBean("l2Bean"); // ensure that override order is correct - assertThat(ctx.getBean("overrideBean", TestBean.class).getName(), is("override-l0")); + assertThat(ctx.getBean("overrideBean", TestBean.class).getName()).isEqualTo("override-l0"); } @Test @@ -96,7 +95,7 @@ public class NestedConfigurationClassTests { ctx.getBean("l2Bean"); // ensure that override order is correct - assertThat(ctx.getBean("overrideBean", TestBean.class).getName(), is("override-l0")); + assertThat(ctx.getBean("overrideBean", TestBean.class).getName()).isEqualTo("override-l0"); } @Test @@ -118,7 +117,7 @@ public class NestedConfigurationClassTests { // ensure that override order is correct and that it is a singleton TestBean ob = ctx.getBean("overrideBean", TestBean.class); - assertThat(ob.getName(), is("override-s1")); + assertThat(ob.getName()).isEqualTo("override-s1"); assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); @@ -146,7 +145,7 @@ public class NestedConfigurationClassTests { // ensure that override order is correct and that it is a singleton TestBean ob = ctx.getBean("overrideBean", TestBean.class); - assertThat(ob.getName(), is("override-s1")); + assertThat(ob.getName()).isEqualTo("override-s1"); assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); @@ -174,7 +173,7 @@ public class NestedConfigurationClassTests { // ensure that override order is correct and that it is a singleton TestBean ob = ctx.getBean("overrideBean", TestBean.class); - assertThat(ob.getName(), is("override-s1")); + assertThat(ob.getName()).isEqualTo("override-s1"); assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/PrimitiveBeanLookupAndAutowiringTests.java b/spring-context/src/test/java/org/springframework/context/annotation/PrimitiveBeanLookupAndAutowiringTests.java index 7b6f48c29c..bb41a9b2c0 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/PrimitiveBeanLookupAndAutowiringTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/PrimitiveBeanLookupAndAutowiringTests.java @@ -23,8 +23,8 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests changes introduced for SPR-8874, allowing beans of primitive types to be looked @@ -47,34 +47,34 @@ public class PrimitiveBeanLookupAndAutowiringTests { public void primitiveLookupByName() { ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); boolean b = ctx.getBean("b", boolean.class); - assertThat(b, equalTo(true)); + assertThat(b).isEqualTo(true); int i = ctx.getBean("i", int.class); - assertThat(i, equalTo(42)); + assertThat(i).isEqualTo(42); } @Test public void primitiveLookupByType() { ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); boolean b = ctx.getBean(boolean.class); - assertThat(b, equalTo(true)); + assertThat(b).isEqualTo(true); int i = ctx.getBean(int.class); - assertThat(i, equalTo(42)); + assertThat(i).isEqualTo(42); } @Test public void primitiveAutowiredInjection() { ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class, AutowiredComponent.class); - assertThat(ctx.getBean(AutowiredComponent.class).b, equalTo(true)); - assertThat(ctx.getBean(AutowiredComponent.class).i, equalTo(42)); + assertThat(ctx.getBean(AutowiredComponent.class).b).isEqualTo(true); + assertThat(ctx.getBean(AutowiredComponent.class).i).isEqualTo(42); } @Test public void primitiveResourceInjection() { ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class, ResourceComponent.class); - assertThat(ctx.getBean(ResourceComponent.class).b, equalTo(true)); - assertThat(ctx.getBean(ResourceComponent.class).i, equalTo(42)); + assertThat(ctx.getBean(ResourceComponent.class).b).isEqualTo(true); + assertThat(ctx.getBean(ResourceComponent.class).i).isEqualTo(42); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java index 534311cbb9..d5c44db657 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java @@ -38,10 +38,8 @@ import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; /** @@ -61,7 +59,7 @@ public class PropertySourceAnnotationTests { ctx.refresh(); assertTrue("property source p1 was not added", ctx.getEnvironment().getPropertySources().contains("p1")); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); // assert that the property source was added last to the set of sources String name; @@ -72,7 +70,7 @@ public class PropertySourceAnnotationTests { } while (iterator.hasNext()); - assertThat(name, is("p1")); + assertThat(name).isEqualTo("p1"); } @Test @@ -82,7 +80,7 @@ public class PropertySourceAnnotationTests { ctx.refresh(); assertTrue("property source p1 was not added", ctx.getEnvironment().getPropertySources().contains("class path resource [org/springframework/context/annotation/p1.properties]")); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); } @Test @@ -105,7 +103,7 @@ public class PropertySourceAnnotationTests { ctx.register(ConfigWithImplicitName.class, P2Config.class); ctx.refresh(); // p2 should 'win' as it was registered last - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p2TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p2TestBean"); } { @@ -113,7 +111,7 @@ public class PropertySourceAnnotationTests { ctx.register(P2Config.class, ConfigWithImplicitName.class); ctx.refresh(); // p1 should 'win' as it was registered last - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); } } @@ -122,7 +120,7 @@ public class PropertySourceAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithImplicitName.class, WithCustomFactory.class); ctx.refresh(); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("P2TESTBEAN")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("P2TESTBEAN"); } @Test @@ -130,7 +128,7 @@ public class PropertySourceAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithImplicitName.class, WithCustomFactoryAsMeta.class); ctx.refresh(); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("P2TESTBEAN")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("P2TESTBEAN"); } @Test @@ -150,7 +148,7 @@ public class PropertySourceAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithUnresolvablePlaceholderAndDefault.class); ctx.refresh(); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); } @Test @@ -159,7 +157,7 @@ public class PropertySourceAnnotationTests { ctx.register(ConfigWithResolvablePlaceholder.class); System.setProperty("path.to.properties", "org/springframework/context/annotation"); ctx.refresh(); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); System.clearProperty("path.to.properties"); } @@ -169,7 +167,7 @@ public class PropertySourceAnnotationTests { ctx.register(ConfigWithResolvablePlaceholderAndFactoryBean.class); System.setProperty("path.to.properties", "org/springframework/context/annotation"); ctx.refresh(); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); System.clearProperty("path.to.properties"); } @@ -188,37 +186,37 @@ public class PropertySourceAnnotationTests { @Test public void withNameAndMultipleResourceLocations() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNameAndMultipleResourceLocations.class); - assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); - assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); + assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue(); + assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue(); // p2 should 'win' as it was registered last - assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); + assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); } @Test public void withMultipleResourceLocations() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithMultipleResourceLocations.class); - assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); - assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); + assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue(); + assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue(); // p2 should 'win' as it was registered last - assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); + assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); } @Test public void withPropertySources() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithPropertySources.class); - assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); - assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); + assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue(); + assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue(); // p2 should 'win' as it was registered last - assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); + assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); } @Test public void withNamedPropertySources() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNamedPropertySources.class); - assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); - assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); + assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue(); + assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue(); // p2 should 'win' as it was registered last - assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); + assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); } @Test @@ -231,16 +229,16 @@ public class PropertySourceAnnotationTests { @Test public void withIgnoredPropertySource() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithIgnoredPropertySource.class); - assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); - assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); + assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue(); + assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue(); } @Test public void withSameSourceImportedInDifferentOrder() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithSameSourceImportedInDifferentOrder.class); - assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); - assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); - assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); + assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue(); + assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue(); + assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); } @Test @@ -248,15 +246,15 @@ public class PropertySourceAnnotationTests { // SPR-10820: p2 should 'win' as it was registered last AnnotationConfigApplicationContext ctxWithName = new AnnotationConfigApplicationContext(ConfigWithNameAndMultipleResourceLocations.class); AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext(ConfigWithMultipleResourceLocations.class); - assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); - assertThat(ctxWithName.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); + assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); + assertThat(ctxWithName.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean"); } @Test public void orderingWithAndWithoutNameAndFourResourceLocations() { // SPR-12198: p4 should 'win' as it was registered last AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext(ConfigWithFourResourceLocations.class); - assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("p4TestBean")); + assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("p4TestBean"); } @Test @@ -267,7 +265,7 @@ public class PropertySourceAnnotationTests { ctxWithoutName.getEnvironment().getPropertySources().addLast(mySource); ctxWithoutName.register(ConfigWithFourResourceLocations.class); ctxWithoutName.refresh(); - assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("myTestBean")); + assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("myTestBean"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java index 828a839a38..20d4538233 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -46,7 +45,7 @@ public class ReflectionUtilsIntegrationTests { m1MethodCount++; } } - assertThat(m1MethodCount, is(1)); + assertThat(m1MethodCount).isEqualTo(1); for (Method method : methods) { if (method.getName().contains("m1")) { assertEquals(method.getReturnType(), Integer.class); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/RoleAndDescriptionAnnotationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/RoleAndDescriptionAnnotationTests.java index b36a907b0d..6a9720c01a 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/RoleAndDescriptionAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/RoleAndDescriptionAnnotationTests.java @@ -22,8 +22,8 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.role.ComponentWithRole; import org.springframework.context.annotation.role.ComponentWithoutRole; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests the use of the @Role and @Description annotation on @Bean methods and @Component classes. @@ -39,12 +39,10 @@ public class RoleAndDescriptionAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Config.class); ctx.refresh(); - assertThat("Expected bean to have ROLE_APPLICATION", - ctx.getBeanDefinition("foo").getRole(), is(BeanDefinition.ROLE_APPLICATION)); - assertThat(ctx.getBeanDefinition("foo").getDescription(), is((Object) null)); - assertThat("Expected bean to have ROLE_INFRASTRUCTURE", - ctx.getBeanDefinition("bar").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE)); - assertThat(ctx.getBeanDefinition("bar").getDescription(), is("A Bean method with a role")); + assertThat(ctx.getBeanDefinition("foo").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION); + assertThat(ctx.getBeanDefinition("foo").getDescription()).isNull(); + assertThat(ctx.getBeanDefinition("bar").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); + assertThat(ctx.getBeanDefinition("bar").getDescription()).isEqualTo("A Bean method with a role"); } @Test @@ -52,12 +50,10 @@ public class RoleAndDescriptionAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ComponentWithoutRole.class, ComponentWithRole.class); ctx.refresh(); - assertThat("Expected bean to have ROLE_APPLICATION", - ctx.getBeanDefinition("componentWithoutRole").getRole(), is(BeanDefinition.ROLE_APPLICATION)); - assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription(), is((Object) null)); - assertThat("Expected bean to have ROLE_INFRASTRUCTURE", - ctx.getBeanDefinition("componentWithRole").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE)); - assertThat(ctx.getBeanDefinition("componentWithRole").getDescription(), is("A Component with a role")); + assertThat(ctx.getBeanDefinition("componentWithoutRole").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION); + assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription()).isNull(); + assertThat(ctx.getBeanDefinition("componentWithRole").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); + assertThat(ctx.getBeanDefinition("componentWithRole").getDescription()).isEqualTo("A Component with a role"); } @@ -66,12 +62,10 @@ public class RoleAndDescriptionAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan("org.springframework.context.annotation.role"); ctx.refresh(); - assertThat("Expected bean to have ROLE_APPLICATION", - ctx.getBeanDefinition("componentWithoutRole").getRole(), is(BeanDefinition.ROLE_APPLICATION)); - assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription(), is((Object) null)); - assertThat("Expected bean to have ROLE_INFRASTRUCTURE", - ctx.getBeanDefinition("componentWithRole").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE)); - assertThat(ctx.getBeanDefinition("componentWithRole").getDescription(), is("A Component with a role")); + assertThat(ctx.getBeanDefinition("componentWithoutRole").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION); + assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription()).isNull(); + assertThat(ctx.getBeanDefinition("componentWithRole").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); + assertThat(ctx.getBeanDefinition("componentWithRole").getDescription()).isEqualTo("A Component with a role"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr12278Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr12278Tests.java index e61cf148c0..c0b8ac4622 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr12278Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr12278Tests.java @@ -21,9 +21,8 @@ import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; /** * @author Stephane Nicoll @@ -43,14 +42,14 @@ public class Spr12278Tests { public void componentSingleConstructor() { this.context = new AnnotationConfigApplicationContext(BaseConfiguration.class, SingleConstructorComponent.class); - assertThat(this.context.getBean(SingleConstructorComponent.class).autowiredName, is("foo")); + assertThat(this.context.getBean(SingleConstructorComponent.class).autowiredName).isEqualTo("foo"); } @Test public void componentTwoConstructorsNoHint() { this.context = new AnnotationConfigApplicationContext(BaseConfiguration.class, TwoConstructorsComponent.class); - assertThat(this.context.getBean(TwoConstructorsComponent.class).name, is("fallback")); + assertThat(this.context.getBean(TwoConstructorsComponent.class).name).isEqualTo("fallback"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr6602Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr6602Tests.java index 54c96a6caf..b5f274ea11 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr6602Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr6602Tests.java @@ -22,9 +22,8 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests to verify that FactoryBean semantics are the same in Configuration @@ -49,16 +48,16 @@ public class Spr6602Tests { Bar bar1 = ctx.getBean(Bar.class); Bar bar2 = ctx.getBean(Bar.class); - assertThat(bar1, is(bar2)); - assertThat(bar1, is(foo.bar)); + assertThat(bar1).isEqualTo(bar2); + assertThat(bar1).isEqualTo(foo.bar); BarFactory barFactory1 = ctx.getBean(BarFactory.class); BarFactory barFactory2 = ctx.getBean(BarFactory.class); - assertThat(barFactory1, is(barFactory2)); + assertThat(barFactory1).isEqualTo(barFactory2); Bar bar3 = barFactory1.getObject(); Bar bar4 = barFactory1.getObject(); - assertThat(bar3, is(not(bar4))); + assertThat(bar3).isNotEqualTo(bar4); } 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 c9639246a8..045846fb16 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 @@ -27,10 +27,8 @@ import org.springframework.beans.factory.config.InstantiationAwareBeanPostProces import org.springframework.beans.factory.support.AbstractBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor} @@ -53,19 +51,19 @@ public class Spr8954Tests { bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); bf.refresh(); - assertThat(bf.getBean("foo"), instanceOf(Foo.class)); - assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); + assertThat(bf.getBean("foo")).isInstanceOf(Foo.class); + assertThat(bf.getBean("&foo")).isInstanceOf(FooFactoryBean.class); - assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue(); @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(1, equalTo(fbBeans.size())); - assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); + assertThat(1).isEqualTo(fbBeans.size()); + assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next()); Map aiBeans = bf.getBeansOfType(AnInterface.class); - assertThat(1, equalTo(aiBeans.size())); - assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); + assertThat(1).isEqualTo(aiBeans.size()); + assertThat("&foo").isEqualTo(aiBeans.keySet().iterator().next()); } @Test @@ -75,16 +73,16 @@ public class Spr8954Tests { bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); bf.refresh(); - assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue(); @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(1, equalTo(fbBeans.size())); - assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); + assertThat(1).isEqualTo(fbBeans.size()); + assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next()); Map aiBeans = bf.getBeansOfType(AnInterface.class); - assertThat(1, equalTo(aiBeans.size())); - assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); + assertThat(1).isEqualTo(aiBeans.size()); + assertThat("&foo").isEqualTo(aiBeans.keySet().iterator().next()); } 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 630d64c8c9..db13aa174a 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 @@ -44,8 +44,7 @@ import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.Colour; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -65,8 +64,8 @@ public class AutowiredConfigurationTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( AutowiredConfigurationTests.class.getSimpleName() + ".xml", AutowiredConfigurationTests.class); - assertThat(context.getBean("colour", Colour.class), equalTo(Colour.RED)); - assertThat(context.getBean("testBean", TestBean.class).getName(), equalTo(Colour.RED.toString())); + assertThat(context.getBean("colour", Colour.class)).isEqualTo(Colour.RED); + assertThat(context.getBean("testBean", TestBean.class).getName()).isEqualTo(Colour.RED.toString()); } @Test @@ -74,8 +73,8 @@ public class AutowiredConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AutowiredMethodConfig.class, ColorConfig.class); - assertThat(context.getBean(Colour.class), equalTo(Colour.RED)); - assertThat(context.getBean(TestBean.class).getName(), equalTo("RED-RED")); + assertThat(context.getBean(Colour.class)).isEqualTo(Colour.RED); + assertThat(context.getBean(TestBean.class).getName()).isEqualTo("RED-RED"); } @Test @@ -83,8 +82,8 @@ public class AutowiredConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( OptionalAutowiredMethodConfig.class, ColorConfig.class); - assertThat(context.getBean(Colour.class), equalTo(Colour.RED)); - assertThat(context.getBean(TestBean.class).getName(), equalTo("RED-RED")); + assertThat(context.getBean(Colour.class)).isEqualTo(Colour.RED); + assertThat(context.getBean(TestBean.class).getName()).isEqualTo("RED-RED"); } @Test @@ -93,7 +92,7 @@ public class AutowiredConfigurationTests { OptionalAutowiredMethodConfig.class); assertTrue(context.getBeansOfType(Colour.class).isEmpty()); - assertThat(context.getBean(TestBean.class).getName(), equalTo("")); + assertThat(context.getBean(TestBean.class).getName()).isEqualTo(""); } @Test @@ -186,10 +185,10 @@ public class AutowiredConfigurationTests { System.setProperty("myProp", "foo"); testBean = context.getBean("testBean", TestBean.class); - assertThat(testBean.getName(), equalTo("foo")); + assertThat(testBean.getName()).isEqualTo("foo"); testBean = context.getBean("testBean2", TestBean.class); - assertThat(testBean.getName(), equalTo("foo")); + assertThat(testBean.getName()).isEqualTo("foo"); System.clearProperty("myProp"); @@ -206,8 +205,8 @@ public class AutowiredConfigurationTests { "AutowiredConfigurationTests-custom.xml", AutowiredConfigurationTests.class); TestBean testBean = context.getBean("testBean", TestBean.class); - assertThat(testBean.getName(), equalTo("localhost")); - assertThat(testBean.getAge(), equalTo(contentLength())); + assertThat(testBean.getName()).isEqualTo("localhost"); + assertThat(testBean.getAge()).isEqualTo(contentLength()); } @Test @@ -218,8 +217,8 @@ public class AutowiredConfigurationTests { context.refresh(); TestBean testBean = context.getBean("testBean", TestBean.class); - assertThat(testBean.getName(), equalTo("localhost")); - assertThat(testBean.getAge(), equalTo(contentLength())); + assertThat(testBean.getName()).isEqualTo("localhost"); + assertThat(testBean.getAge()).isEqualTo(contentLength()); } private int contentLength() throws IOException { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java index 5931ad41d8..4a47bff186 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java @@ -35,8 +35,7 @@ import org.springframework.stereotype.Component; import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -56,8 +55,8 @@ public class BeanMethodQualificationTests { new AnnotationConfigApplicationContext(StandardConfig.class, StandardPojo.class); assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); StandardPojo pojo = ctx.getBean(StandardPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); - assertThat(pojo.testBean2.getName(), equalTo("boring")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); + assertThat(pojo.testBean2.getName()).isEqualTo("boring"); } @Test @@ -66,8 +65,8 @@ public class BeanMethodQualificationTests { new AnnotationConfigApplicationContext(ScopedConfig.class, StandardPojo.class); assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); StandardPojo pojo = ctx.getBean(StandardPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); - assertThat(pojo.testBean2.getName(), equalTo("boring")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); + assertThat(pojo.testBean2.getName()).isEqualTo("boring"); } @Test @@ -76,8 +75,8 @@ public class BeanMethodQualificationTests { new AnnotationConfigApplicationContext(ScopedProxyConfig.class, StandardPojo.class); assertTrue(ctx.getBeanFactory().containsSingleton("testBean1")); // a shared scoped proxy StandardPojo pojo = ctx.getBean(StandardPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); - assertThat(pojo.testBean2.getName(), equalTo("boring")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); + assertThat(pojo.testBean2.getName()).isEqualTo("boring"); } @Test @@ -89,10 +88,10 @@ public class BeanMethodQualificationTests { assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), "testBean2", ctx.getDefaultListableBeanFactory())); CustomPojo pojo = ctx.getBean(CustomPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); TestBean testBean2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType( ctx.getDefaultListableBeanFactory(), TestBean.class, "boring"); - assertThat(testBean2.getName(), equalTo("boring")); + assertThat(testBean2.getName()).isEqualTo("boring"); } @Test @@ -106,7 +105,7 @@ public class BeanMethodQualificationTests { assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), "testBean2", ctx.getDefaultListableBeanFactory())); CustomPojo pojo = ctx.getBean(CustomPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); } @Test @@ -120,7 +119,7 @@ public class BeanMethodQualificationTests { assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); CustomPojo pojo = ctx.getBean(CustomPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); } @Test @@ -129,7 +128,7 @@ public class BeanMethodQualificationTests { new AnnotationConfigApplicationContext(CustomConfigWithAttributeOverride.class, CustomPojo.class); assertFalse(ctx.getBeanFactory().containsSingleton("testBeanX")); CustomPojo pojo = ctx.getBean(CustomPojo.class); - assertThat(pojo.testBean.getName(), equalTo("interesting")); + assertThat(pojo.testBean.getName()).isEqualTo("interesting"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationBeanNameTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationBeanNameTests.java index 77175f58a4..2660f1c894 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationBeanNameTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationBeanNameTests.java @@ -27,8 +27,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Component; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests ensuring that configuration class bean names as expressed via @Configuration @@ -45,10 +45,10 @@ public class ConfigurationBeanNameTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(A.class); ctx.refresh(); - assertThat(ctx.containsBean("outer"), is(true)); - assertThat(ctx.containsBean("imported"), is(true)); - assertThat(ctx.containsBean("nested"), is(true)); - assertThat(ctx.containsBean("nestedBean"), is(true)); + assertThat(ctx.containsBean("outer")).isTrue(); + assertThat(ctx.containsBean("imported")).isTrue(); + assertThat(ctx.containsBean("nested")).isTrue(); + assertThat(ctx.containsBean("nestedBean")).isTrue(); } @Test @@ -56,10 +56,10 @@ public class ConfigurationBeanNameTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(A.B.class); ctx.refresh(); - assertThat(ctx.containsBean("outer"), is(false)); - assertThat(ctx.containsBean("imported"), is(false)); - assertThat(ctx.containsBean("nested"), is(true)); - assertThat(ctx.containsBean("nestedBean"), is(true)); + assertThat(ctx.containsBean("outer")).isFalse(); + assertThat(ctx.containsBean("imported")).isFalse(); + assertThat(ctx.containsBean("nested")).isTrue(); + assertThat(ctx.containsBean("nestedBean")).isTrue(); } @Test @@ -74,10 +74,10 @@ public class ConfigurationBeanNameTests { }); ctx.register(A.class); ctx.refresh(); - assertThat(ctx.containsBean("custom-outer"), is(true)); - assertThat(ctx.containsBean("custom-imported"), is(true)); - assertThat(ctx.containsBean("custom-nested"), is(true)); - assertThat(ctx.containsBean("nestedBean"), is(true)); + assertThat(ctx.containsBean("custom-outer")).isTrue(); + assertThat(ctx.containsBean("custom-imported")).isTrue(); + assertThat(ctx.containsBean("custom-nested")).isTrue(); + assertThat(ctx.containsBean("nestedBean")).isTrue(); } @Configuration("outer") diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassAspectIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassAspectIntegrationTests.java index 513cd57102..7c2d0133ab 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassAspectIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassAspectIntegrationTests.java @@ -35,8 +35,8 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * System tests covering use of AspectJ {@link Aspect}s in conjunction with {@link Configuration} classes. @@ -73,9 +73,9 @@ public class ConfigurationClassAspectIntegrationTests { ctx.refresh(); TestBean testBean = ctx.getBean("testBean", TestBean.class); - assertThat(testBean.getName(), equalTo("name")); + assertThat(testBean.getName()).isEqualTo("name"); testBean.absquatulate(); - assertThat(testBean.getName(), equalTo("advisedName")); + assertThat(testBean.getName()).isEqualTo("advisedName"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassWithPlaceholderConfigurerBeanTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassWithPlaceholderConfigurerBeanTests.java index 5587510bf7..c23d3bc816 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassWithPlaceholderConfigurerBeanTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassWithPlaceholderConfigurerBeanTests.java @@ -26,9 +26,8 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * A configuration class that registers a non-static placeholder configurer {@code @Bean} @@ -71,7 +70,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests { TestBean testBean = ctx.getBean(TestBean.class); // Proof that the @Value field did not get set: - assertThat(testBean.getName(), nullValue()); + assertThat(testBean.getName()).isNull(); } @Test @@ -84,7 +83,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests { System.clearProperty("test.name"); TestBean testBean = ctx.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("foo")); + assertThat(testBean.getName()).isEqualTo("foo"); } @Test @@ -98,7 +97,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests { System.clearProperty("test.name"); TestBean testBean = ctx.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("foo")); + assertThat(testBean.getName()).isEqualTo("foo"); } @Test @@ -110,7 +109,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests { ctx.refresh(); TestBean testBean = ctx.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("bar")); + assertThat(testBean.getName()).isEqualTo("bar"); } @Test @@ -122,7 +121,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests { ctx.refresh(); TestBean testBean = ctx.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("bar")); + assertThat(testBean.getName()).isEqualTo("bar"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationMetaAnnotationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationMetaAnnotationTests.java index 2dc7d5734f..0b22c7f714 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationMetaAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationMetaAnnotationTests.java @@ -26,9 +26,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Ensures that @Configuration is supported properly as a meta-annotation. @@ -42,10 +41,10 @@ public class ConfigurationMetaAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Config.class); ctx.refresh(); - assertThat(ctx.containsBean("customName"), is(true)); + assertThat(ctx.containsBean("customName")).isTrue(); TestBean a = ctx.getBean("a", TestBean.class); TestBean b = ctx.getBean("b", TestBean.class); - assertThat(b, sameInstance(a.getSpouse())); + assertThat(b).isSameAs(a.getSpouse()); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportAnnotationDetectionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportAnnotationDetectionTests.java index db5f3a4bbd..bbbff6c724 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportAnnotationDetectionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportAnnotationDetectionTests.java @@ -29,8 +29,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests that @Import may be used both as a locally declared and meta-declared @@ -48,8 +48,8 @@ public class ImportAnnotationDetectionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(MultiMetaImportConfig.class); ctx.refresh(); - assertThat(ctx.containsBean("testBean1"), is(true)); - assertThat(ctx.containsBean("testBean2"), is(true)); + assertThat(ctx.containsBean("testBean1")).isTrue(); + assertThat(ctx.containsBean("testBean2")).isTrue(); } @Test @@ -57,9 +57,9 @@ public class ImportAnnotationDetectionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(MultiMetaImportConfigWithLocalImport.class); ctx.refresh(); - assertThat(ctx.containsBean("testBean1"), is(true)); - assertThat(ctx.containsBean("testBean2"), is(true)); - assertThat(ctx.containsBean("testBean3"), is(true)); + assertThat(ctx.containsBean("testBean1")).isTrue(); + assertThat(ctx.containsBean("testBean2")).isTrue(); + assertThat(ctx.containsBean("testBean3")).isTrue(); } @Test @@ -67,9 +67,9 @@ public class ImportAnnotationDetectionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(MultiMetaImportConfigWithLocalImportWithBeanOverride.class); ctx.refresh(); - assertThat(ctx.containsBean("testBean1"), is(true)); - assertThat(ctx.containsBean("testBean2"), is(true)); - assertThat(ctx.getBean("testBean2", TestBean.class).getName(), is("2a")); + assertThat(ctx.containsBean("testBean1")).isTrue(); + assertThat(ctx.containsBean("testBean2")).isTrue(); + assertThat(ctx.getBean("testBean2", TestBean.class).getName()).isEqualTo("2a"); } @Test @@ -77,9 +77,9 @@ public class ImportAnnotationDetectionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ImportFromBean.class); ctx.refresh(); - assertThat(ctx.containsBean("importAnnotationDetectionTests.ImportFromBean"), is(true)); - assertThat(ctx.containsBean("testBean1"), is(true)); - assertThat(ctx.getBean("testBean1", TestBean.class).getName(), is("1")); + assertThat(ctx.containsBean("importAnnotationDetectionTests.ImportFromBean")).isTrue(); + assertThat(ctx.containsBean("testBean1")).isTrue(); + assertThat(ctx.getBean("testBean1", TestBean.class).getName()).isEqualTo("1"); } @Configuration diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java index 569ba436c1..296cb9169c 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java @@ -34,8 +34,7 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -107,7 +106,7 @@ public class ImportResourceTests { public void importXmlWithAutowiredConfig() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlAutowiredConfig.class); String name = ctx.getBean("xmlBeanName", String.class); - assertThat(name, equalTo("xml.declared")); + assertThat(name).isEqualTo("xml.declared"); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java index cc0597e3c3..d1dd4166a1 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java @@ -29,9 +29,7 @@ import org.springframework.context.annotation.Import; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -54,7 +52,7 @@ public class ImportTests { private void assertBeanDefinitionCount(int expectedCount, Class... classes) { DefaultListableBeanFactory beanFactory = processConfigurationClasses(classes); - assertThat(beanFactory.getBeanDefinitionCount(), equalTo(expectedCount)); + assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(expectedCount); beanFactory.preInstantiateSingletons(); for (Class clazz : classes) { beanFactory.getBean(clazz); @@ -70,7 +68,7 @@ public class ImportTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(ConfigurationWithImportAnnotation.class.getName())); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertThat(beanFactory.getBeanDefinitionCount(), equalTo(configClasses + beansInClasses)); + assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(configClasses + beansInClasses); } @Test @@ -178,8 +176,8 @@ public class ImportTests { WithMultipleArgumentsThatWillCauseDuplication.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertThat(beanFactory.getBeanDefinitionCount(), equalTo(4)); - assertThat(beanFactory.getBean("foo", ITestBean.class).getName(), equalTo("foo2")); + assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(4); + assertThat(beanFactory.getBean("foo", ITestBean.class).getName()).isEqualTo("foo2"); } @Configuration @@ -341,8 +339,8 @@ public class ImportTests { ctx.register(B.class); ctx.refresh(); System.out.println(ctx.getBeanFactory()); - assertThat(ctx.getBeanNamesForType(B.class)[0], is("config-b")); - assertThat(ctx.getBeanNamesForType(A.class)[0], is("config-a")); + assertThat(ctx.getBeanNamesForType(B.class)[0]).isEqualTo("config-b"); + assertThat(ctx.getBeanNamesForType(A.class)[0]).isEqualTo("config-a"); } @Configuration("config-a") diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java index ada079a821..267263e756 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java @@ -27,8 +27,7 @@ import org.springframework.context.annotation.Import; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -73,8 +72,9 @@ public class ImportedConfigurationClassEnhancementTests { Config config = ctx.getBean(Config.class); TestBean testBean1 = config.autowiredConfig.testBean(); TestBean testBean2 = config.autowiredConfig.testBean(); - assertThat("got two distinct instances of testBean when singleton scoping was expected", - testBean1, sameInstance(testBean2)); + assertThat(testBean1) + .as("got two distinct instances of testBean when singleton scoping was expected") + .isSameAs(testBean2); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/PackagePrivateBeanMethodInheritanceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/PackagePrivateBeanMethodInheritanceTests.java index 98e917cb87..31ec2bce43 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/PackagePrivateBeanMethodInheritanceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/PackagePrivateBeanMethodInheritanceTests.java @@ -22,9 +22,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Reproduces SPR-8756, which has been marked as "won't fix" for reasons @@ -42,7 +41,7 @@ public class PackagePrivateBeanMethodInheritanceTests { Foo foo1 = ctx.getBean("foo1", Foo.class); Foo foo2 = ctx.getBean("foo2", Foo.class); ctx.getBean("packagePrivateBar", Bar.class); // <-- i.e. @Bean was registered - assertThat(foo1.bar, not(is(foo2.bar))); // <-- i.e. @Bean *not* enhanced + assertThat(foo1.bar).isNotEqualTo(foo2.bar); // <-- i.e. @Bean *not* enhanced } @Test @@ -52,8 +51,8 @@ public class PackagePrivateBeanMethodInheritanceTests { ctx.refresh(); Foo foo1 = ctx.getBean("foo1", Foo.class); Foo foo2 = ctx.getBean("foo2", Foo.class); - ctx.getBean("protectedBar", Bar.class); // <-- i.e. @Bean was registered - assertThat(foo1.bar, is(foo2.bar)); // <-- i.e. @Bean *was* enhanced + ctx.getBean("protectedBar", Bar.class); // <-- i.e. @Bean was registered + assertThat(foo1.bar).isEqualTo(foo2.bar); // <-- i.e. @Bean *was* enhanced } public static class Foo { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10744Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10744Tests.java index abfba58ea1..0521f28cb0 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10744Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10744Tests.java @@ -25,9 +25,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; + + + /** * @author Phillip Webb @@ -48,19 +49,19 @@ public class Spr10744Tests { Foo bean1 = context.getBean("foo", Foo.class); Foo bean2 = context.getBean("foo", Foo.class); - assertThat(bean1, sameInstance(bean2)); + assertThat(bean1).isSameAs(bean2); // Should not have invoked constructor for the proxy instance - assertThat(createCount, equalTo(0)); - assertThat(scopeCount, equalTo(0)); + assertThat(createCount).isEqualTo(0); + assertThat(scopeCount).isEqualTo(0); // Proxy mode should create new scoped object on each method call bean1.getMessage(); - assertThat(createCount, equalTo(1)); - assertThat(scopeCount, equalTo(1)); + assertThat(createCount).isEqualTo(1); + assertThat(scopeCount).isEqualTo(1); bean1.getMessage(); - assertThat(createCount, equalTo(2)); - assertThat(scopeCount, equalTo(2)); + assertThat(createCount).isEqualTo(2); + assertThat(scopeCount).isEqualTo(2); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java index 040a8aeea8..7d3907bfa6 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java @@ -28,8 +28,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; public class Spr7167Tests { @@ -38,9 +37,9 @@ public class Spr7167Tests { public void test() { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class); - assertThat("someDependency was not post processed", - ctx.getBeanFactory().getBeanDefinition("someDependency").getDescription(), - equalTo("post processed by MyPostProcessor")); + assertThat(ctx.getBeanFactory().getBeanDefinition("someDependency").getDescription()) + .as("someDependency was not post processed") + .isEqualTo("post processed by MyPostProcessor"); MyConfig config = ctx.getBean(MyConfig.class); assertTrue("Config class was not enhanced", ClassUtils.isCglibProxy(config)); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/spr9031/Spr9031Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/spr9031/Spr9031Tests.java index a87706fe7a..e23bb7f586 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/spr9031/Spr9031Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/spr9031/Spr9031Tests.java @@ -29,9 +29,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.configuration.spr9031.scanpackage.Spr9031Component; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests cornering bug SPR-9031. @@ -50,7 +49,7 @@ public class Spr9031Tests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(HighLevelConfig.class); ctx.refresh(); - assertThat(ctx.getBean(LowLevelConfig.class).scanned, not(nullValue())); + assertThat(ctx.getBean(LowLevelConfig.class).scanned).isNotNull(); } /** @@ -62,7 +61,7 @@ public class Spr9031Tests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(LowLevelConfig.class); ctx.refresh(); - assertThat(ctx.getBean(LowLevelConfig.class).scanned, not(nullValue())); + assertThat(ctx.getBean(LowLevelConfig.class).scanned).isNotNull(); } @Configuration diff --git a/spring-context/src/test/java/org/springframework/context/annotation/spr10546/Spr10546Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/spr10546/Spr10546Tests.java index 57c63c6578..f325a367cf 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/spr10546/Spr10546Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/spr10546/Spr10546Tests.java @@ -25,8 +25,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.spr10546.scanpackage.AEnclosingConfig; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Rob Winch @@ -64,7 +64,7 @@ public class Spr10546Tests { context = ctx; ctx.scan(AEnclosingConfig.class.getPackage().getName()); ctx.refresh(); - assertThat(context.getBean("myBean",String.class), equalTo("myBean")); + assertThat(context.getBean("myBean",String.class)).isEqualTo("myBean"); } @Test @@ -143,7 +143,7 @@ public class Spr10546Tests { private void assertLoadsMyBean(Class... annotatedClasses) { context = new AnnotationConfigApplicationContext(annotatedClasses); - assertThat(context.getBean("myBean",String.class), equalTo("myBean")); + assertThat(context.getBean("myBean",String.class)).isEqualTo("myBean"); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java index ef5d9391b6..529fd71063 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java @@ -24,8 +24,8 @@ import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests cornering the regression reported in SPR-8761. @@ -43,7 +43,7 @@ public class Spr8761Tests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan(getClass().getPackage().getName()); ctx.refresh(); - assertThat(ctx.containsBean("withNestedAnnotation"), is(true)); + assertThat(ctx.containsBean("withNestedAnnotation")).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java b/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java index 7412886c8b..5779f0947c 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 @@ -64,10 +64,9 @@ import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; @@ -548,7 +547,7 @@ public class AnnotationDrivenEventListenerTests { assertTrue(listener.order.isEmpty()); this.context.publishEvent("whatever"); - assertThat(listener.order, contains("first", "second", "third")); + assertThat(listener.order).contains("first", "second", "third"); } @Test @Ignore // SPR-15122 @@ -556,7 +555,7 @@ public class AnnotationDrivenEventListenerTests { load(EventOnPostConstruct.class, OrderedTestListener.class); OrderedTestListener listener = this.context.getBean(OrderedTestListener.class); - assertThat(listener.order, contains("first", "second", "third")); + assertThat(listener.order).contains("first", "second", "third"); } diff --git a/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java index 6b1572e8f3..efd66b7a77 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java @@ -24,8 +24,7 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.mock.env.MockPropertySource; import org.springframework.tests.sample.beans.TestBean; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; /** @@ -49,7 +48,7 @@ public class EnvironmentAccessorIntegrationTests { ctx.getEnvironment().getPropertySources().addFirst(new MockPropertySource().withProperty("my.name", "myBean")); ctx.refresh(); - assertThat(ctx.getBean(TestBean.class).getName(), equalTo("myBean")); + assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("myBean"); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexLoaderTests.java b/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexLoaderTests.java index d4ae8e09bc..d828876add 100644 --- a/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexLoaderTests.java +++ b/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexLoaderTests.java @@ -23,12 +23,13 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; + + + + + /** * Tests for {@link CandidateComponentsIndexLoader}. @@ -40,7 +41,7 @@ public class CandidateComponentsIndexLoaderTests { @Test public void validateIndexIsDisabledByDefault() { CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex(null); - assertThat("No spring.components should be available at the default location", index, is(nullValue())); + assertThat(index).as("No spring.components should be available at the default location").isNull(); } @Test @@ -49,9 +50,9 @@ public class CandidateComponentsIndexLoaderTests { CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), new ClassPathResource("spring.components", getClass()))); Set components = index.getCandidateTypes("org.springframework", "foo"); - assertThat(components, containsInAnyOrder( + assertThat(components).contains( "org.springframework.context.index.Sample1", - "org.springframework.context.index.Sample2")); + "org.springframework.context.index.Sample2"); } @Test @@ -60,8 +61,8 @@ public class CandidateComponentsIndexLoaderTests { CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), new ClassPathResource("spring.components", getClass()))); Set components = index.getCandidateTypes("org.springframework", "biz"); - assertThat(components, containsInAnyOrder( - "org.springframework.context.index.Sample3")); + assertThat(components).contains( + "org.springframework.context.index.Sample3"); } @Test @@ -70,7 +71,7 @@ public class CandidateComponentsIndexLoaderTests { CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), new ClassPathResource("spring.components", getClass()))); Set components = index.getCandidateTypes("org.springframework", "none"); - assertThat(components, hasSize(0)); + assertThat(components).isEmpty(); } @Test @@ -79,14 +80,14 @@ public class CandidateComponentsIndexLoaderTests { CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), new ClassPathResource("spring.components", getClass()))); Set components = index.getCandidateTypes("com.example", "foo"); - assertThat(components, hasSize(0)); + assertThat(components).isEmpty(); } @Test public void loadIndexNoSpringComponentsResource() { CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex( CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader())); - assertThat(index, is(nullValue())); + assertThat(index).isNull(); } @Test @@ -94,7 +95,7 @@ public class CandidateComponentsIndexLoaderTests { CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex( CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), new ClassPathResource("empty-spring.components", getClass()))); - assertThat(index, is(nullValue())); + assertThat(index).isNull(); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexTests.java b/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexTests.java index f0cd573bd1..274f26d2b1 100644 --- a/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexTests.java +++ b/spring-context/src/test/java/org/springframework/context/index/CandidateComponentsIndexTests.java @@ -23,10 +23,11 @@ import java.util.Set; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasSize; +import static org.assertj.core.api.Assertions.assertThat; + + + + /** * Tests for {@link CandidateComponentsIndex}. @@ -40,8 +41,8 @@ public class CandidateComponentsIndexTests { CandidateComponentsIndex index = new CandidateComponentsIndex( Collections.singletonList(createSampleProperties())); Set actual = index.getCandidateTypes("com.example.service", "service"); - assertThat(actual, containsInAnyOrder("com.example.service.One", - "com.example.service.sub.Two", "com.example.service.Three")); + assertThat(actual).contains("com.example.service.One", + "com.example.service.sub.Two", "com.example.service.Three"); } @Test @@ -49,7 +50,7 @@ public class CandidateComponentsIndexTests { CandidateComponentsIndex index = new CandidateComponentsIndex( Collections.singletonList(createSampleProperties())); Set actual = index.getCandidateTypes("com.example.service.sub", "service"); - assertThat(actual, containsInAnyOrder("com.example.service.sub.Two")); + assertThat(actual).contains("com.example.service.sub.Two"); } @Test @@ -57,7 +58,7 @@ public class CandidateComponentsIndexTests { CandidateComponentsIndex index = new CandidateComponentsIndex( Collections.singletonList(createSampleProperties())); Set actual = index.getCandidateTypes("com.example.service.none", "service"); - assertThat(actual, hasSize(0)); + assertThat(actual).isEmpty(); } @Test @@ -65,7 +66,7 @@ public class CandidateComponentsIndexTests { CandidateComponentsIndex index = new CandidateComponentsIndex( Collections.singletonList(createSampleProperties())); Set actual = index.getCandidateTypes("com.example.service", "entity"); - assertThat(actual, hasSize(0)); + assertThat(actual).isEmpty(); } @Test @@ -73,10 +74,10 @@ public class CandidateComponentsIndexTests { CandidateComponentsIndex index = new CandidateComponentsIndex(Arrays.asList( createProperties("com.example.Foo", "service"), createProperties("com.example.Foo", "entity"))); - assertThat(index.getCandidateTypes("com.example", "service"), - contains("com.example.Foo")); - assertThat(index.getCandidateTypes("com.example", "entity"), - contains("com.example.Foo")); + assertThat(index.getCandidateTypes("com.example", "service")) + .contains("com.example.Foo"); + assertThat(index.getCandidateTypes("com.example", "entity")) + .contains("com.example.Foo"); } private static Properties createProperties(String key, String stereotypes) { 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 89d406dd7c..1f99694cbc 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 @@ -34,9 +34,8 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.ResourceTestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertTrue; /** @@ -142,8 +141,8 @@ public class ConversionServiceFactoryBeanTests { public ComplexConstructorArgument(Map> map) { assertTrue(!map.isEmpty()); - assertThat(map.keySet().iterator().next(), instanceOf(String.class)); - assertThat(map.values().iterator().next(), instanceOf(Class.class)); + 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/EnvironmentIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/EnvironmentIntegrationTests.java index 9bb40b0dcb..2f0454b2e4 100644 --- a/spring-context/src/test/java/org/springframework/context/support/EnvironmentIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/EnvironmentIntegrationTests.java @@ -24,9 +24,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; -import static org.hamcrest.CoreMatchers.anyOf; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests covering the integration of the {@link Environment} into @@ -47,10 +46,7 @@ public class EnvironmentIntegrationTests { child.refresh(); ConfigurableEnvironment env = child.getBean(ConfigurableEnvironment.class); - assertThat("unknown env", env, anyOf( - sameInstance(parent.getEnvironment()), - sameInstance(child.getEnvironment()))); - assertThat("expected child ctx env", env, sameInstance(child.getEnvironment())); + assertThat(env).isSameAs(child.getEnvironment()); child.close(); parent.close(); diff --git a/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java index b0f879d18f..bc6f5f2fd0 100644 --- a/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java @@ -32,8 +32,8 @@ import org.springframework.core.env.StandardEnvironmentTests; import org.springframework.stereotype.Component; import static java.lang.String.format; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests integration between Environment and SecurityManagers. See SPR-9970. @@ -78,7 +78,7 @@ public class EnvironmentSecurityManagerIntegrationTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); reader.register(C1.class); - assertThat(bf.containsBean("c1"), is(true)); + assertThat(bf.containsBean("c1")).isTrue(); } @Test @@ -108,7 +108,7 @@ public class EnvironmentSecurityManagerIntegrationTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); reader.register(C1.class); - assertThat(bf.containsBean("c1"), is(false)); + assertThat(bf.containsBean("c1")).isFalse(); } diff --git a/spring-context/src/test/java/org/springframework/context/support/GenericXmlApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/GenericXmlApplicationContextTests.java index ebb48b4a8c..961d2718ff 100644 --- a/spring-context/src/test/java/org/springframework/context/support/GenericXmlApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/GenericXmlApplicationContextTests.java @@ -21,8 +21,8 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.util.ClassUtils; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link GenericXmlApplicationContext}. @@ -43,7 +43,7 @@ public class GenericXmlApplicationContextTests { @Test public void classRelativeResourceLoading_ctor() { ApplicationContext ctx = new GenericXmlApplicationContext(RELATIVE_CLASS, RESOURCE_NAME); - assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue(); } @Test @@ -51,13 +51,13 @@ public class GenericXmlApplicationContextTests { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load(RELATIVE_CLASS, RESOURCE_NAME); ctx.refresh(); - assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue(); } @Test public void fullyQualifiedResourceLoading_ctor() { ApplicationContext ctx = new GenericXmlApplicationContext(FQ_RESOURCE_PATH); - assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue(); } @Test @@ -65,6 +65,6 @@ public class GenericXmlApplicationContextTests { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load(FQ_RESOURCE_PATH); ctx.refresh(); - assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue(); } } 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 4c26e9b448..ee7bb82303 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 @@ -33,13 +33,9 @@ import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.env.MockPropertySource; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; @@ -66,8 +62,8 @@ public class PropertySourcesPlaceholderConfigurerTests { PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); ppc.setEnvironment(env); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue")); - assertThat(ppc.getAppliedPropertySources(), not(nullValue())); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("myValue"); + assertThat(ppc.getAppliedPropertySources()).isNotNull(); } @Test @@ -82,7 +78,7 @@ public class PropertySourcesPlaceholderConfigurerTests { Resource resource = new ClassPathResource("PropertySourcesPlaceholderConfigurerTests.properties", this.getClass()); ppc.setLocation(resource); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("foo")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("foo"); } @Test @@ -109,7 +105,7 @@ public class PropertySourcesPlaceholderConfigurerTests { PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); ppc.setPropertySources(propertySources); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("foo")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("foo"); assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next()); } @@ -129,7 +125,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "env")); ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}"); assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next()); } @@ -152,7 +148,7 @@ public class PropertySourcesPlaceholderConfigurerTests { }}); ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}"); } @Test @@ -180,7 +176,7 @@ public class PropertySourcesPlaceholderConfigurerTests { PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}"); } @Test @@ -215,7 +211,7 @@ public class PropertySourcesPlaceholderConfigurerTests { }}); ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("${bogus}")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${bogus}"); } @Test @@ -240,7 +236,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setEnvironment(env); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("bar"); } @SuppressWarnings("serial") @@ -260,10 +256,10 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setEnvironment(new MockEnvironment().withProperty("foo", "enclosing")); ppc.postProcessBeanFactory(bf); if (override) { - assertThat(bf.getBean(TestBean.class).getName(), equalTo("local")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("local"); } else { - assertThat(bf.getBean(TestBean.class).getName(), equalTo("enclosing")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("enclosing"); } } @@ -287,8 +283,8 @@ public class PropertySourcesPlaceholderConfigurerTests { System.clearProperty("key1"); System.clearProperty("key2"); - assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value")); - assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("systemKey1Value"); + assertThat(bf.getBean(TestBean.class).getSex()).isEqualTo("${key2}"); } @Test @@ -301,7 +297,7 @@ public class PropertySourcesPlaceholderConfigurerTests { .getBeanDefinition()); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "customNull")); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), nullValue()); + assertThat(bf.getBean(TestBean.class).getName()).isNull(); } @Test @@ -313,7 +309,7 @@ public class PropertySourcesPlaceholderConfigurerTests { .getBeanDefinition()); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue ")); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue ")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo(" myValue "); } @Test @@ -326,7 +322,7 @@ public class PropertySourcesPlaceholderConfigurerTests { .getBeanDefinition()); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue ")); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue")); + assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("myValue"); } @Test @@ -351,7 +347,7 @@ public class PropertySourcesPlaceholderConfigurerTests { .addPropertyValue("jedi", "${jedi:false}") .getBeanDefinition()); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(TestBean.class).isJedi(), equalTo(true)); + assertThat(bf.getBean(TestBean.class).isJedi()).isEqualTo(true); } @Test @@ -370,7 +366,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setEnvironment(env); ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.of("myValue"))); + assertThat(bf.getBean(OptionalTestBean.class).getName()).isEqualTo(Optional.of("myValue")); } @Test @@ -390,7 +386,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setNullValue(""); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.empty())); + assertThat(bf.getBean(OptionalTestBean.class).getName()).isEqualTo(Optional.empty()); } diff --git a/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java b/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java index d1b0646d1e..58b2351409 100644 --- a/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java @@ -28,8 +28,7 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; /** @@ -79,17 +78,17 @@ public class SerializableBeanFactoryMemoryLeakTests { } private void assertFactoryCountThroughoutLifecycle(ConfigurableApplicationContext ctx) throws Exception { - assertThat(serializableFactoryCount(), equalTo(0)); + assertThat(serializableFactoryCount()).isEqualTo(0); try { ctx.refresh(); - assertThat(serializableFactoryCount(), equalTo(1)); + assertThat(serializableFactoryCount()).isEqualTo(1); ctx.close(); } catch (BeanCreationException ex) { // ignore - this is expected on refresh() for failure case tests } finally { - assertThat(serializableFactoryCount(), equalTo(0)); + assertThat(serializableFactoryCount()).isEqualTo(0); } } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/DateFormatterTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormatterTests.java index 600fbe520e..e5699d8101 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/DateFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/DateFormatterTests.java @@ -30,10 +30,11 @@ import org.junit.Test; import org.springframework.format.annotation.DateTimeFormat.ISO; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; + + + /** * Tests for {@link DateFormatter}. @@ -51,8 +52,8 @@ public class DateFormatterTests { DateFormatter formatter = new DateFormatter(); formatter.setTimeZone(UTC); Date date = getDate(2009, Calendar.JUNE, 1); - assertThat(formatter.print(date, Locale.US), is("Jun 1, 2009")); - assertThat(formatter.parse("Jun 1, 2009", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("Jun 1, 2009"); + assertThat(formatter.parse("Jun 1, 2009", Locale.US)).isEqualTo(date); } @Test @@ -60,8 +61,8 @@ public class DateFormatterTests { DateFormatter formatter = new DateFormatter("yyyy-MM-dd"); formatter.setTimeZone(UTC); Date date = getDate(2009, Calendar.JUNE, 1); - assertThat(formatter.print(date, Locale.US), is("2009-06-01")); - assertThat(formatter.parse("2009-06-01", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("2009-06-01"); + assertThat(formatter.parse("2009-06-01", Locale.US)).isEqualTo(date); } @Test @@ -70,8 +71,8 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setStyle(DateFormat.SHORT); Date date = getDate(2009, Calendar.JUNE, 1); - assertThat(formatter.print(date, Locale.US), is("6/1/09")); - assertThat(formatter.parse("6/1/09", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("6/1/09"); + assertThat(formatter.parse("6/1/09", Locale.US)).isEqualTo(date); } @Test @@ -80,8 +81,8 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setStyle(DateFormat.MEDIUM); Date date = getDate(2009, Calendar.JUNE, 1); - assertThat(formatter.print(date, Locale.US), is("Jun 1, 2009")); - assertThat(formatter.parse("Jun 1, 2009", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("Jun 1, 2009"); + assertThat(formatter.parse("Jun 1, 2009", Locale.US)).isEqualTo(date); } @Test @@ -90,8 +91,8 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setStyle(DateFormat.LONG); Date date = getDate(2009, Calendar.JUNE, 1); - assertThat(formatter.print(date, Locale.US), is("June 1, 2009")); - assertThat(formatter.parse("June 1, 2009", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("June 1, 2009"); + assertThat(formatter.parse("June 1, 2009", Locale.US)).isEqualTo(date); } @Test @@ -100,8 +101,8 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setStyle(DateFormat.FULL); Date date = getDate(2009, Calendar.JUNE, 1); - assertThat(formatter.print(date, Locale.US), is("Monday, June 1, 2009")); - assertThat(formatter.parse("Monday, June 1, 2009", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("Monday, June 1, 2009"); + assertThat(formatter.parse("Monday, June 1, 2009", Locale.US)).isEqualTo(date); } @Test @@ -110,9 +111,9 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setIso(ISO.DATE); Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3); - assertThat(formatter.print(date, Locale.US), is("2009-06-01")); - assertThat(formatter.parse("2009-6-01", Locale.US), - is(getDate(2009, Calendar.JUNE, 1))); + assertThat(formatter.print(date, Locale.US)).isEqualTo("2009-06-01"); + assertThat(formatter.parse("2009-6-01", Locale.US)) + .isEqualTo(getDate(2009, Calendar.JUNE, 1)); } @Test @@ -121,9 +122,9 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setIso(ISO.TIME); Date date = getDate(2009, Calendar.JANUARY, 1, 14, 23, 5, 3); - assertThat(formatter.print(date, Locale.US), is("14:23:05.003Z")); - assertThat(formatter.parse("14:23:05.003Z", Locale.US), - is(getDate(1970, Calendar.JANUARY, 1, 14, 23, 5, 3))); + assertThat(formatter.print(date, Locale.US)).isEqualTo("14:23:05.003Z"); + assertThat(formatter.parse("14:23:05.003Z", Locale.US)) + .isEqualTo(getDate(1970, Calendar.JANUARY, 1, 14, 23, 5, 3)); } @Test @@ -132,8 +133,8 @@ public class DateFormatterTests { formatter.setTimeZone(UTC); formatter.setIso(ISO.DATE_TIME); Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3); - assertThat(formatter.print(date, Locale.US), is("2009-06-01T14:23:05.003Z")); - assertThat(formatter.parse("2009-06-01T14:23:05.003Z", Locale.US), is(date)); + assertThat(formatter.print(date, Locale.US)).isEqualTo("2009-06-01T14:23:05.003Z"); + assertThat(formatter.parse("2009-06-01T14:23:05.003Z", Locale.US)).isEqualTo(date); } @Test @@ -162,10 +163,12 @@ public class DateFormatterTests { formatter.setStylePattern(style); DateTimeFormatter jodaFormatter = DateTimeFormat.forStyle(style).withLocale(locale).withZone(DateTimeZone.UTC); String jodaPrinted = jodaFormatter.print(date.getTime()); - assertThat("Unable to print style pattern " + style, - formatter.print(date, locale), is(equalTo(jodaPrinted))); - assertThat("Unable to parse style pattern " + style, - formatter.parse(jodaPrinted, locale), is(equalTo(date))); + assertThat(formatter.print(date, locale)) + .as("Unable to print style pattern " + style) + .isEqualTo(jodaPrinted); + assertThat(formatter.parse(jodaPrinted, locale)) + .as("Unable to parse style pattern " + style) + .isEqualTo(date); } @Test @@ -187,16 +190,16 @@ public class DateFormatterTests { formatter.setPattern("yyyy"); Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3); - assertThat("uses pattern",formatter.print(date, Locale.US), is("2009")); + assertThat(formatter.print(date, Locale.US)).as("uses pattern").isEqualTo("2009"); formatter.setPattern(""); - assertThat("uses ISO", formatter.print(date, Locale.US), is("2009-06-01T14:23:05.003Z")); + assertThat(formatter.print(date, Locale.US)).as("uses ISO").isEqualTo("2009-06-01T14:23:05.003Z"); formatter.setIso(ISO.NONE); - assertThat("uses style pattern", formatter.print(date, Locale.US), is("June 1, 2009")); + assertThat(formatter.print(date, Locale.US)).as("uses style pattern").isEqualTo("June 1, 2009"); formatter.setStylePattern(""); - assertThat("uses style", formatter.print(date, Locale.US), is("6/1/09")); + assertThat(formatter.print(date, Locale.US)).as("uses style").isEqualTo("6/1/09"); } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java index 2a63e2a8c2..8e75001da5 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java @@ -36,8 +36,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -218,7 +217,7 @@ public class DateFormattingTests { public void stringToDateWithoutGlobalFormat() { String string = "Sat, 12 Aug 1995 13:30:00 GM"; Date date = this.conversionService.convert(string, Date.class); - assertThat(date, equalTo(new Date(string))); + assertThat(date).isEqualTo(new Date(string)); } @Test // SPR-10105 diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java index 01b4aa0918..3766075893 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java @@ -20,10 +20,11 @@ import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; + + + + /** * @author Phillip Webb @@ -36,28 +37,28 @@ public class DateTimeFormatterFactoryBeanTests { @Test public void isSingleton() { - assertThat(factory.isSingleton(), is(true)); + assertThat(factory.isSingleton()).isTrue(); } @Test @SuppressWarnings("rawtypes") public void getObjectType() { - assertThat(factory.getObjectType(), is(equalTo((Class) DateTimeFormatter.class))); + assertThat(factory.getObjectType()).isEqualTo(DateTimeFormatter.class); } @Test public void getObject() { factory.afterPropertiesSet(); - assertThat(factory.getObject(), is(equalTo(DateTimeFormat.mediumDateTime()))); + assertThat(factory.getObject()).isEqualTo(DateTimeFormat.mediumDateTime()); } @Test public void getObjectIsAlwaysSingleton() { factory.afterPropertiesSet(); DateTimeFormatter formatter = factory.getObject(); - assertThat(formatter, is(equalTo(DateTimeFormat.mediumDateTime()))); + assertThat(formatter).isEqualTo(DateTimeFormat.mediumDateTime()); factory.setStyle("LL"); - assertThat(factory.getObject(), is(sameInstance(formatter))); + assertThat(factory.getObject()).isSameAs(formatter); } } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java index a56ba2980a..da2f14c493 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java @@ -27,11 +27,7 @@ import org.junit.Test; import org.springframework.format.annotation.DateTimeFormat.ISO; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -55,27 +51,27 @@ public class DateTimeFormatterFactoryTests { @Test public void createDateTimeFormatter() { - assertThat(factory.createDateTimeFormatter(), is(equalTo(DateTimeFormat.mediumDateTime()))); + assertThat(factory.createDateTimeFormatter()).isEqualTo(DateTimeFormat.mediumDateTime()); } @Test public void createDateTimeFormatterWithPattern() { factory = new DateTimeFormatterFactory("yyyyMMddHHmmss"); DateTimeFormatter formatter = factory.createDateTimeFormatter(); - assertThat(formatter.print(dateTime), is("20091021121000")); + assertThat(formatter.print(dateTime)).isEqualTo("20091021121000"); } @Test public void createDateTimeFormatterWithNullFallback() { DateTimeFormatter formatter = factory.createDateTimeFormatter(null); - assertThat(formatter, is(nullValue())); + assertThat(formatter).isNull(); } @Test public void createDateTimeFormatterWithFallback() { DateTimeFormatter fallback = DateTimeFormat.forStyle("LL"); DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback); - assertThat(formatter, is(sameInstance(fallback))); + assertThat(formatter).isSameAs(fallback); } @Test @@ -86,10 +82,10 @@ public class DateTimeFormatterFactoryTests { assertTrue(value.endsWith("12:10 PM")); factory.setIso(ISO.DATE); - assertThat(applyLocale(factory.createDateTimeFormatter()).print(dateTime), is("2009-10-21")); + assertThat(applyLocale(factory.createDateTimeFormatter()).print(dateTime)).isEqualTo("2009-10-21"); factory.setPattern("yyyyMMddHHmmss"); - assertThat(factory.createDateTimeFormatter().print(dateTime), is("20091021121000")); + assertThat(factory.createDateTimeFormatter().print(dateTime)).isEqualTo("20091021121000"); } @Test @@ -99,7 +95,7 @@ public class DateTimeFormatterFactoryTests { DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TEST_TIMEZONE); DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone); String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200"); - assertThat(factory.createDateTimeFormatter().print(dateTime), is("20091021121000 " + offset)); + assertThat(factory.createDateTimeFormatter().print(dateTime)).isEqualTo("20091021121000 " + offset); } private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) { diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java index 660b32ce55..3804e53b04 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java @@ -46,8 +46,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -453,7 +452,7 @@ public class JodaTimeFormattingTests { public void stringToDateWithoutGlobalFormat() { String string = "Sat, 12 Aug 1995 13:30:00 GM"; Date date = this.conversionService.convert(string, Date.class); - assertThat(date, equalTo(new Date(string))); + assertThat(date).isEqualTo(new Date(string)); } @Test // SPR-10105 diff --git a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryBeanTests.java index 55019fd8e0..5d22c354de 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryBeanTests.java @@ -21,10 +21,11 @@ import java.time.format.FormatStyle; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; + + + + /** * @author Phillip Webb @@ -37,27 +38,27 @@ public class DateTimeFormatterFactoryBeanTests { @Test public void isSingleton() { - assertThat(factory.isSingleton(), is(true)); + assertThat(factory.isSingleton()).isTrue(); } @Test public void getObjectType() { - assertThat(factory.getObjectType(), is(equalTo(DateTimeFormatter.class))); + assertThat(factory.getObjectType()).isEqualTo(DateTimeFormatter.class); } @Test public void getObject() { factory.afterPropertiesSet(); - assertThat(factory.getObject().toString(), is(equalTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()))); + assertThat(factory.getObject().toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()); } @Test public void getObjectIsAlwaysSingleton() { factory.afterPropertiesSet(); DateTimeFormatter formatter = factory.getObject(); - assertThat(formatter.toString(), is(equalTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()))); + assertThat(formatter.toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()); factory.setStylePattern("LL"); - assertThat(factory.getObject(), is(sameInstance(formatter))); + assertThat(factory.getObject()).isSameAs(formatter); } } 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 3034c14146..645fce3d62 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 @@ -28,11 +28,7 @@ import org.junit.Test; import org.springframework.format.annotation.DateTimeFormat.ISO; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -56,27 +52,27 @@ public class DateTimeFormatterFactoryTests { @Test public void createDateTimeFormatter() { - assertThat(factory.createDateTimeFormatter().toString(), is(equalTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()))); + assertThat(factory.createDateTimeFormatter().toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()); } @Test public void createDateTimeFormatterWithPattern() { factory = new DateTimeFormatterFactory("yyyyMMddHHmmss"); DateTimeFormatter formatter = factory.createDateTimeFormatter(); - assertThat(formatter.format(dateTime), is("20091021121000")); + assertThat(formatter.format(dateTime)).isEqualTo("20091021121000"); } @Test public void createDateTimeFormatterWithNullFallback() { DateTimeFormatter formatter = factory.createDateTimeFormatter(null); - assertThat(formatter, is(nullValue())); + assertThat(formatter).isNull(); } @Test public void createDateTimeFormatterWithFallback() { DateTimeFormatter fallback = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback); - assertThat(formatter, is(sameInstance(fallback))); + assertThat(formatter).isSameAs(fallback); } @Test @@ -87,10 +83,10 @@ public class DateTimeFormatterFactoryTests { assertTrue(value.endsWith("12:10 PM")); factory.setIso(ISO.DATE); - assertThat(applyLocale(factory.createDateTimeFormatter()).format(dateTime), is("2009-10-21")); + assertThat(applyLocale(factory.createDateTimeFormatter()).format(dateTime)).isEqualTo("2009-10-21"); factory.setPattern("yyyyMMddHHmmss"); - assertThat(factory.createDateTimeFormatter().format(dateTime), is("20091021121000")); + assertThat(factory.createDateTimeFormatter().format(dateTime)).isEqualTo("20091021121000"); } @Test @@ -100,7 +96,7 @@ public class DateTimeFormatterFactoryTests { ZoneId dateTimeZone = TEST_TIMEZONE.toZoneId(); ZonedDateTime dateTime = ZonedDateTime.of(2009, 10, 21, 12, 10, 00, 00, dateTimeZone); String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200"); - assertThat(factory.createDateTimeFormatter().format(dateTime), is("20091021121000 " + offset)); + assertThat(factory.createDateTimeFormatter().format(dateTime)).isEqualTo("20091021121000 " + offset); } private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) { diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiLocatorDelegateTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiLocatorDelegateTests.java index 6f4725d620..8b7c869d88 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiLocatorDelegateTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiLocatorDelegateTests.java @@ -21,8 +21,9 @@ import javax.naming.spi.NamingManager; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; + + /** * Tests for {@link JndiLocatorDelegate}. @@ -40,7 +41,7 @@ public class JndiLocatorDelegateTests { builderField.set(null, null); try { - assertThat(JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable(), equalTo(false)); + assertThat(JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()).isEqualTo(false); } finally { builderField.set(null, oldBuilder); diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java index 98c8536629..e8f17baf12 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.tests.mock.jndi.SimpleNamingContext; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -40,7 +38,7 @@ public class JndiPropertySourceTests { @Test public void nonExistentProperty() { JndiPropertySource ps = new JndiPropertySource("jndiProperties"); - assertThat(ps.getProperty("bogus"), nullValue()); + assertThat(ps.getProperty("bogus")).isNull(); } @Test @@ -59,7 +57,7 @@ public class JndiPropertySourceTests { jndiLocator.setJndiTemplate(jndiTemplate); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); - assertThat(ps.getProperty("p1"), equalTo("v1")); + assertThat(ps.getProperty("p1")).isEqualTo("v1"); } @Test @@ -78,7 +76,7 @@ public class JndiPropertySourceTests { jndiLocator.setJndiTemplate(jndiTemplate); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); - assertThat(ps.getProperty("p1"), equalTo("v1")); + assertThat(ps.getProperty("p1")).isEqualTo("v1"); } @Test @@ -92,7 +90,7 @@ public class JndiPropertySourceTests { jndiLocator.setResourceRef(true); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); - assertThat(ps.getProperty("propertyKey:defaultValue"), nullValue()); + assertThat(ps.getProperty("propertyKey:defaultValue")).isNull(); } @Test @@ -107,7 +105,7 @@ public class JndiPropertySourceTests { jndiLocator.setResourceRef(false); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); - assertThat(ps.getProperty("my:key"), equalTo("my:value")); + assertThat(ps.getProperty("my:key")).isEqualTo("my:value"); } } 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 a04afcea8e..40edfc3884 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 @@ -21,8 +21,8 @@ import java.lang.annotation.RetentionPolicy; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link AnnotationAsyncExecutionInterceptor}. @@ -38,23 +38,23 @@ public class AnnotationAsyncExecutionInterceptorTests { AnnotationAsyncExecutionInterceptor i = new AnnotationAsyncExecutionInterceptor(null); { // method level class C { @Async("qMethod") void m() { } } - assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qMethod")); + assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMethod"); } { // class level @Async("qClass") class C { void m() { } } - assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qClass")); + assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qClass"); } { // method and class level -> method value overrides @Async("qClass") class C { @Async("qMethod") void m() { } } - assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qMethod")); + assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMethod"); } { // method and class level -> method value, even if empty, overrides @Async("qClass") class C { @Async void m() { } } - assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("")); + assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo(""); } { // meta annotation with qualifier @MyAsync class C { void m() { } } - assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qMeta")); + assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMeta"); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java index b8bb9014f2..436e3bbd11 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java @@ -54,12 +54,8 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -79,7 +75,7 @@ public class EnableAsyncTests { ctx.refresh(); AsyncBean asyncBean = ctx.getBean(AsyncBean.class); - assertThat(AopUtils.isAopProxy(asyncBean), is(true)); + assertThat(AopUtils.isAopProxy(asyncBean)).isTrue(); asyncBean.work(); ctx.close(); } @@ -92,7 +88,7 @@ public class EnableAsyncTests { AsyncBeanUser asyncBeanUser = ctx.getBean(AsyncBeanUser.class); AsyncBean asyncBean = asyncBeanUser.getAsyncBean(); - assertThat(AopUtils.isAopProxy(asyncBean), is(true)); + assertThat(AopUtils.isAopProxy(asyncBean)).isTrue(); asyncBean.work(); ctx.close(); } @@ -125,13 +121,13 @@ public class EnableAsyncTests { AsyncBeanWithExecutorQualifiedByName asyncBean = ctx.getBean(AsyncBeanWithExecutorQualifiedByName.class); Future workerThread0 = asyncBean.work0(); - assertThat(workerThread0.get().getName(), not(anyOf(startsWith("e1-"), startsWith("otherExecutor-")))); + assertThat(workerThread0.get().getName()).doesNotStartWith("e1-").doesNotStartWith("otherExecutor-"); Future workerThread = asyncBean.work(); - assertThat(workerThread.get().getName(), startsWith("e1-")); + assertThat(workerThread.get().getName()).startsWith("e1-"); Future workerThread2 = asyncBean.work2(); - assertThat(workerThread2.get().getName(), startsWith("otherExecutor-")); + assertThat(workerThread2.get().getName()).startsWith("otherExecutor-"); Future workerThread3 = asyncBean.work3(); - assertThat(workerThread3.get().getName(), startsWith("otherExecutor-")); + assertThat(workerThread3.get().getName()).startsWith("otherExecutor-"); ctx.close(); } @@ -143,7 +139,7 @@ public class EnableAsyncTests { ctx.refresh(); AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class); - assertThat(bpp.getOrder(), is(Ordered.LOWEST_PRECEDENCE)); + assertThat(bpp.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); ctx.close(); } @@ -155,7 +151,7 @@ public class EnableAsyncTests { ctx.refresh(); AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class); - assertThat(bpp.getOrder(), is(Ordered.HIGHEST_PRECEDENCE)); + assertThat(bpp.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); ctx.close(); } @@ -206,7 +202,7 @@ public class EnableAsyncTests { .atMost(500, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> asyncBean.getThreadOfExecution() != null); - assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); + assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-"); ctx.close(); } @@ -224,7 +220,7 @@ public class EnableAsyncTests { .atMost(500, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> asyncBean.getThreadOfExecution() != null); - assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); + assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-"); ctx.close(); } @@ -263,7 +259,7 @@ public class EnableAsyncTests { .atMost(500, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> asyncBean.getThreadOfExecution() != null); - assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Post-")); + assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Post-"); ctx.close(); } @@ -300,7 +296,7 @@ public class EnableAsyncTests { .atMost(500, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> asyncBean.getThreadOfExecution() != null); - assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); + assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-"); ctx.close(); } @@ -316,7 +312,7 @@ public class EnableAsyncTests { .atMost(500, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> asyncBean.getThreadOfExecution() != null); - assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); + assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-"); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java index 454be27a36..78ec311653 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java @@ -35,12 +35,7 @@ import org.springframework.scheduling.config.TaskManagementConfigUtils; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.both; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.hamcrest.Matchers.startsWith; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -72,7 +67,7 @@ public class EnableSchedulingTests { assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); Thread.sleep(100); - assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); + assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); } @Test @@ -83,7 +78,7 @@ public class EnableSchedulingTests { assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); Thread.sleep(100); - assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); + assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); } @Test @@ -94,8 +89,8 @@ public class EnableSchedulingTests { assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); Thread.sleep(100); - assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); - assertThat(ctx.getBean(ExplicitSchedulerConfig.class).threadName, startsWith("explicitScheduler-")); + assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); + assertThat(ctx.getBean(ExplicitSchedulerConfig.class).threadName).startsWith("explicitScheduler-"); assertTrue(Arrays.asList(ctx.getDefaultListableBeanFactory().getDependentBeans("myTaskScheduler")).contains( TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); } @@ -114,8 +109,8 @@ public class EnableSchedulingTests { assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); Thread.sleep(100); - assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); - assertThat(ctx.getBean(ExplicitScheduledTaskRegistrarConfig.class).threadName, startsWith("explicitScheduler1")); + assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); + assertThat(ctx.getBean(ExplicitScheduledTaskRegistrarConfig.class).threadName).startsWith("explicitScheduler1"); } @Test @@ -137,7 +132,7 @@ public class EnableSchedulingTests { SchedulingEnabled_withAmbiguousTaskSchedulers_andSingleTask_disambiguatedByScheduledTaskRegistrar.class); Thread.sleep(100); - assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread, startsWith("explicitScheduler2-")); + assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread).startsWith("explicitScheduler2-"); } @Test @@ -148,7 +143,7 @@ public class EnableSchedulingTests { SchedulingEnabled_withAmbiguousTaskSchedulers_andSingleTask_disambiguatedBySchedulerNameAttribute.class); Thread.sleep(100); - assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread, startsWith("explicitScheduler2-")); + assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread).startsWith("explicitScheduler2-"); } @Test @@ -158,7 +153,7 @@ public class EnableSchedulingTests { ctx = new AnnotationConfigApplicationContext(SchedulingEnabled_withTaskAddedVia_configureTasks.class); Thread.sleep(100); - assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread, startsWith("taskScheduler-")); + assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread).startsWith("taskScheduler-"); } @Test @@ -168,7 +163,7 @@ public class EnableSchedulingTests { ctx = new AnnotationConfigApplicationContext(TriggerTaskConfig.class); Thread.sleep(100); - assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThan(1)); + assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThan(1); } @Test @@ -182,7 +177,7 @@ public class EnableSchedulingTests { // The @Scheduled method should have been called at least once but // not more times than the delay allows. - assertThat(counter.get(), both(greaterThan(0)).and(lessThanOrEqualTo(10))); + assertThat(counter.get()).isBetween(1, 10); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java index 8e86ea8a5d..29b52734f1 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java @@ -30,8 +30,7 @@ import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.support.ScheduledMethodRunnable; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -110,7 +109,7 @@ public class ScheduledTasksBeanDefinitionParserTests { List tasks = (List) new DirectFieldAccessor( this.registrar).getPropertyValue("triggerTasks"); assertEquals(1, tasks.size()); - assertThat(tasks.get(0).getTrigger(), instanceOf(TestTrigger.class)); + assertThat(tasks.get(0).getTrigger()).isInstanceOf(TestTrigger.class); } diff --git a/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java index 759ba4d324..276cb78b48 100644 --- a/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java @@ -21,9 +21,10 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.DefaultMessageCodesResolver.Format; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; + + + /** * Tests for {@link DefaultMessageCodesResolver}. @@ -37,27 +38,27 @@ public class DefaultMessageCodesResolverTests { @Test public void shouldResolveMessageCode() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "errorCode.objectName", - "errorCode" }))); + "errorCode"); } @Test public void shouldResolveFieldMessageCode() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "errorCode.objectName.field", "errorCode.field", "errorCode.org.springframework.tests.sample.beans.TestBean", - "errorCode" }))); + "errorCode"); } @Test public void shouldResolveIndexedFieldMessageCode() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "a.b[3].c[5].d", TestBean.class); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "errorCode.objectName.a.b[3].c[5].d", "errorCode.objectName.a.b[3].c.d", "errorCode.objectName.a.b.c.d", @@ -66,16 +67,16 @@ public class DefaultMessageCodesResolverTests { "errorCode.a.b.c.d", "errorCode.d", "errorCode.org.springframework.tests.sample.beans.TestBean", - "errorCode" }))); + "errorCode"); } @Test public void shouldResolveMessageCodeWithPrefix() throws Exception { resolver.setPrefix("prefix."); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "prefix.errorCode.objectName", - "prefix.errorCode" }))); + "prefix.errorCode"); } @Test @@ -83,11 +84,11 @@ public class DefaultMessageCodesResolverTests { resolver.setPrefix("prefix."); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "prefix.errorCode.objectName.field", "prefix.errorCode.field", "prefix.errorCode.org.springframework.tests.sample.beans.TestBean", - "prefix.errorCode" }))); + "prefix.errorCode"); } @Test @@ -95,41 +96,41 @@ public class DefaultMessageCodesResolverTests { resolver.setPrefix(null); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "errorCode.objectName.field", "errorCode.field", "errorCode.org.springframework.tests.sample.beans.TestBean", - "errorCode" }))); + "errorCode"); } @Test public void shouldSupportMalformedIndexField() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field[", TestBean.class); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "errorCode.objectName.field[", "errorCode.field[", "errorCode.org.springframework.tests.sample.beans.TestBean", - "errorCode" }))); + "errorCode"); } @Test public void shouldSupportNullFieldType() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", null); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "errorCode.objectName.field", "errorCode.field", - "errorCode" }))); + "errorCode"); } @Test public void shouldSupportPostfixFormat() throws Exception { resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "objectName.errorCode", - "errorCode" }))); + "errorCode"); } @Test @@ -137,11 +138,11 @@ public class DefaultMessageCodesResolverTests { resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "objectName.field.errorCode", "field.errorCode", "org.springframework.tests.sample.beans.TestBean.errorCode", - "errorCode" }))); + "errorCode"); } @Test @@ -154,9 +155,9 @@ public class DefaultMessageCodesResolverTests { } }); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); - assertThat(codes, is(equalTo(new String[] { + assertThat(codes).containsExactly( "CUSTOM-errorCode.objectName", - "CUSTOM-errorCode" }))); + "CUSTOM-errorCode"); } } 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 9e29ef4fcd..3fa7d8a260 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 @@ -54,9 +54,7 @@ import org.springframework.validation.FieldError; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.StringContains.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -98,13 +96,13 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); - assertThat(errors.getFieldErrorCount("password"), is(1)); - assertThat(errors.getFieldValue("password"), is("pass")); + assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); + assertThat(errors.getFieldValue("password")).isEqualTo("pass"); FieldError error = errors.getFieldError("password"); assertNotNull(error); - assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Size of Password is must be between 8 and 128")); + assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Size of Password is must be between 8 and 128"); assertTrue(error.contains(ConstraintViolation.class)); - assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); + assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); } @Test // SPR-13406 @@ -116,13 +114,13 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); - assertThat(errors.getFieldErrorCount("password"), is(1)); - assertThat(errors.getFieldValue("password"), is("password")); + assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); + assertThat(errors.getFieldValue("password")).isEqualTo("password"); FieldError error = errors.getFieldError("password"); assertNotNull(error); - assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Password must be same value as Password(Confirm)")); + assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)"); assertTrue(error.contains(ConstraintViolation.class)); - assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); + assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); } @Test // SPR-13406 @@ -134,19 +132,19 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); - assertThat(errors.getFieldErrorCount("email"), is(1)); - assertThat(errors.getFieldValue("email"), is("test@example.com")); - assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); + assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); + assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com"); + assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); assertNotNull(error1); assertNotNull(error2); - assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); - assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); + assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); + assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); assertTrue(error1.contains(ConstraintViolation.class)); - assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); + assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); assertTrue(error2.contains(ConstraintViolation.class)); - assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); + assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @Test // SPR-15123 @@ -160,19 +158,19 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); - assertThat(errors.getFieldErrorCount("email"), is(1)); - assertThat(errors.getFieldValue("email"), is("test@example.com")); - assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); + assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); + assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com"); + assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); assertNotNull(error1); assertNotNull(error2); - assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); - assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); + assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); + assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); assertTrue(error1.contains(ConstraintViolation.class)); - assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); + assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); assertTrue(error2.contains(ConstraintViolation.class)); - assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); + assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @Test @@ -184,13 +182,13 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); - assertThat(errors.getFieldErrorCount("email"), is(1)); - assertThat(errors.getFieldValue("email"), is("X")); + assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); + assertThat(errors.getFieldValue("email")).isEqualTo("X"); FieldError error = errors.getFieldError("email"); assertNotNull(error); - assertThat(messageSource.getMessage(error, Locale.ENGLISH), containsString("[\\w.'-]{1,}@[\\w.'-]{1,}")); + assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}"); assertTrue(error.contains(ConstraintViolation.class)); - assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); + assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); } @Test // SPR-16177 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 b458fbc448..dbfc1f5f71 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java @@ -52,8 +52,6 @@ import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -136,8 +134,9 @@ public class ValidatorFactoryTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); validator.validate(person, errors); assertEquals(1, errors.getErrorCount()); - assertThat("Field/Value type mismatch", errors.getFieldError("address").getRejectedValue(), - instanceOf(ValidAddress.class)); + assertThat(errors.getFieldError("address").getRejectedValue()) + .as("Field/Value type mismatch") + .isInstanceOf(ValidAddress.class); } @Test diff --git a/spring-core/spring-core.gradle b/spring-core/spring-core.gradle index 51a3c50647..2b80b71b94 100644 --- a/spring-core/spring-core.gradle +++ b/spring-core/spring-core.gradle @@ -87,6 +87,7 @@ dependencies { testCompile("org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}") testCompile("com.google.code.findbugs:jsr305:3.0.2") testCompile("org.xmlunit:xmlunit-matchers:2.6.2") + testCompile("org.xmlunit:xmlunit-assertj:2.6.2") testCompile("javax.xml.bind:jaxb-api:2.3.1") testCompile("com.fasterxml.woodstox:woodstox-core:5.2.0") { exclude group: "stax", module: "stax-api" diff --git a/spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java b/spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java index 23691826cc..737beb7263 100644 --- a/spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java +++ b/spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java @@ -34,17 +34,15 @@ import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; +import org.assertj.core.api.Assertions; import org.junit.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; import static org.springframework.core.CollectionFactory.createApproximateCollection; import static org.springframework.core.CollectionFactory.createApproximateMap; import static org.springframework.core.CollectionFactory.createCollection; @@ -158,7 +156,7 @@ public class CollectionFactoryTests { @Test public void createApproximateCollectionFromEmptyHashSet() { Collection set = createApproximateCollection(new HashSet(), 2); - assertThat(set, is(empty())); + Assertions.assertThat(set).isEmpty(); } @Test @@ -166,25 +164,25 @@ public class CollectionFactoryTests { HashSet hashSet = new HashSet<>(); hashSet.add("foo"); Collection set = createApproximateCollection(hashSet, 2); - assertThat(set, is(empty())); + assertThat(set).isEmpty(); } @Test public void createApproximateCollectionFromEmptyEnumSet() { Collection colors = createApproximateCollection(EnumSet.noneOf(Color.class), 2); - assertThat(colors, is(empty())); + assertThat(colors).isEmpty(); } @Test public void createApproximateCollectionFromNonEmptyEnumSet() { Collection colors = createApproximateCollection(EnumSet.of(Color.BLUE), 2); - assertThat(colors, is(empty())); + assertThat(colors).isEmpty(); } @Test public void createApproximateMapFromEmptyHashMap() { Map map = createApproximateMap(new HashMap(), 2); - assertThat(map.size(), is(0)); + assertThat(map).isEmpty(); } @Test @@ -192,13 +190,13 @@ public class CollectionFactoryTests { Map hashMap = new HashMap<>(); hashMap.put("foo", "bar"); Map map = createApproximateMap(hashMap, 2); - assertThat(map.size(), is(0)); + assertThat(map).isEmpty(); } @Test public void createApproximateMapFromEmptyEnumMap() { Map colors = createApproximateMap(new EnumMap(Color.class), 2); - assertThat(colors.size(), is(0)); + assertThat(colors).isEmpty(); } @Test @@ -206,38 +204,38 @@ public class CollectionFactoryTests { EnumMap enumMap = new EnumMap<>(Color.class); enumMap.put(Color.BLUE, "blue"); Map colors = createApproximateMap(enumMap, 2); - assertThat(colors.size(), is(0)); + assertThat(colors).isEmpty(); } @Test public void createsCollectionsCorrectly() { // interfaces - assertThat(createCollection(List.class, 0), is(instanceOf(ArrayList.class))); - assertThat(createCollection(Set.class, 0), is(instanceOf(LinkedHashSet.class))); - assertThat(createCollection(Collection.class, 0), is(instanceOf(LinkedHashSet.class))); - assertThat(createCollection(SortedSet.class, 0), is(instanceOf(TreeSet.class))); - assertThat(createCollection(NavigableSet.class, 0), is(instanceOf(TreeSet.class))); + assertThat(createCollection(List.class, 0)).isInstanceOf(ArrayList.class); + assertThat(createCollection(Set.class, 0)).isInstanceOf(LinkedHashSet.class); + assertThat(createCollection(Collection.class, 0)).isInstanceOf(LinkedHashSet.class); + assertThat(createCollection(SortedSet.class, 0)).isInstanceOf(TreeSet.class); + assertThat(createCollection(NavigableSet.class, 0)).isInstanceOf(TreeSet.class); - assertThat(createCollection(List.class, String.class, 0), is(instanceOf(ArrayList.class))); - assertThat(createCollection(Set.class, String.class, 0), is(instanceOf(LinkedHashSet.class))); - assertThat(createCollection(Collection.class, String.class, 0), is(instanceOf(LinkedHashSet.class))); - assertThat(createCollection(SortedSet.class, String.class, 0), is(instanceOf(TreeSet.class))); - assertThat(createCollection(NavigableSet.class, String.class, 0), is(instanceOf(TreeSet.class))); + assertThat(createCollection(List.class, String.class, 0)).isInstanceOf(ArrayList.class); + assertThat(createCollection(Set.class, String.class, 0)).isInstanceOf(LinkedHashSet.class); + assertThat(createCollection(Collection.class, String.class, 0)).isInstanceOf(LinkedHashSet.class); + assertThat(createCollection(SortedSet.class, String.class, 0)).isInstanceOf(TreeSet.class); + assertThat(createCollection(NavigableSet.class, String.class, 0)).isInstanceOf(TreeSet.class); // concrete types - assertThat(createCollection(HashSet.class, 0), is(instanceOf(HashSet.class))); - assertThat(createCollection(HashSet.class, String.class, 0), is(instanceOf(HashSet.class))); + assertThat(createCollection(HashSet.class, 0)).isInstanceOf(HashSet.class); + assertThat(createCollection(HashSet.class, String.class, 0)).isInstanceOf(HashSet.class); } @Test public void createsEnumSet() { - assertThat(createCollection(EnumSet.class, Color.class, 0), is(instanceOf(EnumSet.class))); + assertThat(createCollection(EnumSet.class, Color.class, 0)).isInstanceOf(EnumSet.class); } @Test // SPR-17619 public void createsEnumSetSubclass() { EnumSet enumSet = EnumSet.noneOf(Color.class); - assertThat(createCollection(enumSet.getClass(), Color.class, 0), is(instanceOf(enumSet.getClass()))); + assertThat(createCollection(enumSet.getClass(), Color.class, 0)).isInstanceOf(enumSet.getClass()); } @Test @@ -261,25 +259,25 @@ public class CollectionFactoryTests { @Test public void createsMapsCorrectly() { // interfaces - assertThat(createMap(Map.class, 0), is(instanceOf(LinkedHashMap.class))); - assertThat(createMap(SortedMap.class, 0), is(instanceOf(TreeMap.class))); - assertThat(createMap(NavigableMap.class, 0), is(instanceOf(TreeMap.class))); - assertThat(createMap(MultiValueMap.class, 0), is(instanceOf(LinkedMultiValueMap.class))); + assertThat(createMap(Map.class, 0)).isInstanceOf(LinkedHashMap.class); + assertThat(createMap(SortedMap.class, 0)).isInstanceOf(TreeMap.class); + assertThat(createMap(NavigableMap.class, 0)).isInstanceOf(TreeMap.class); + assertThat(createMap(MultiValueMap.class, 0)).isInstanceOf(LinkedMultiValueMap.class); - assertThat(createMap(Map.class, String.class, 0), is(instanceOf(LinkedHashMap.class))); - assertThat(createMap(SortedMap.class, String.class, 0), is(instanceOf(TreeMap.class))); - assertThat(createMap(NavigableMap.class, String.class, 0), is(instanceOf(TreeMap.class))); - assertThat(createMap(MultiValueMap.class, String.class, 0), is(instanceOf(LinkedMultiValueMap.class))); + assertThat(createMap(Map.class, String.class, 0)).isInstanceOf(LinkedHashMap.class); + assertThat(createMap(SortedMap.class, String.class, 0)).isInstanceOf(TreeMap.class); + assertThat(createMap(NavigableMap.class, String.class, 0)).isInstanceOf(TreeMap.class); + assertThat(createMap(MultiValueMap.class, String.class, 0)).isInstanceOf(LinkedMultiValueMap.class); // concrete types - assertThat(createMap(HashMap.class, 0), is(instanceOf(HashMap.class))); + assertThat(createMap(HashMap.class, 0)).isInstanceOf(HashMap.class); - assertThat(createMap(HashMap.class, String.class, 0), is(instanceOf(HashMap.class))); + assertThat(createMap(HashMap.class, String.class, 0)).isInstanceOf(HashMap.class); } @Test public void createsEnumMap() { - assertThat(createMap(EnumMap.class, Color.class, 0), is(instanceOf(EnumMap.class))); + assertThat(createMap(EnumMap.class, Color.class, 0)).isInstanceOf(EnumMap.class); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java b/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java index 0c54b06f74..7fcb3fc280 100644 --- a/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java @@ -27,8 +27,7 @@ import java.util.Map; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -112,25 +111,25 @@ public class GenericTypeResolverTests { Map map; map = GenericTypeResolver.getTypeVariableMap(MySimpleInterfaceType.class); - assertThat(map.toString(), equalTo("{T=class java.lang.String}")); + assertThat(map.toString()).isEqualTo("{T=class java.lang.String}"); map = GenericTypeResolver.getTypeVariableMap(MyCollectionInterfaceType.class); - assertThat(map.toString(), equalTo("{T=java.util.Collection}")); + assertThat(map.toString()).isEqualTo("{T=java.util.Collection}"); map = GenericTypeResolver.getTypeVariableMap(MyCollectionSuperclassType.class); - assertThat(map.toString(), equalTo("{T=java.util.Collection}")); + assertThat(map.toString()).isEqualTo("{T=java.util.Collection}"); map = GenericTypeResolver.getTypeVariableMap(MySimpleTypeWithMethods.class); - assertThat(map.toString(), equalTo("{T=class java.lang.Integer}")); + assertThat(map.toString()).isEqualTo("{T=class java.lang.Integer}"); map = GenericTypeResolver.getTypeVariableMap(TopLevelClass.class); - assertThat(map.toString(), equalTo("{}")); + assertThat(map.toString()).isEqualTo("{}"); map = GenericTypeResolver.getTypeVariableMap(TypedTopLevelClass.class); - assertThat(map.toString(), equalTo("{T=class java.lang.Integer}")); + assertThat(map.toString()).isEqualTo("{T=class java.lang.Integer}"); map = GenericTypeResolver.getTypeVariableMap(TypedTopLevelClass.TypedNested.class); - assertThat(map.size(), equalTo(2)); + assertThat(map.size()).isEqualTo(2); Type t = null; Type x = null; for (Map.Entry entry : map.entrySet()) { @@ -141,8 +140,8 @@ public class GenericTypeResolverTests { x = entry.getValue(); } } - assertThat(t, equalTo((Type) Integer.class)); - assertThat(x, equalTo((Type) Long.class)); + assertThat(t).isEqualTo(Integer.class); + assertThat(x).isEqualTo(Long.class); } @Test // SPR-11030 @@ -162,14 +161,14 @@ public class GenericTypeResolverTests { MethodParameter methodParameter = MethodParameter.forExecutable( WithArrayBase.class.getDeclaredMethod("array", Object[].class), 0); Class resolved = GenericTypeResolver.resolveParameterType(methodParameter, WithArray.class); - assertThat(resolved, equalTo((Class) Object[].class)); + assertThat(resolved).isEqualTo(Object[].class); } @Test // SPR-11044 public void getGenericsOnArrayFromReturnCannotBeResolved() throws Exception { Class resolved = GenericTypeResolver.resolveReturnType( WithArrayBase.class.getDeclaredMethod("array", Object[].class), WithArray.class); - assertThat(resolved, equalTo((Class) Object[].class)); + assertThat(resolved).isEqualTo(Object[].class); } @Test // SPR-11763 diff --git a/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java b/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java index bffe19a01c..4e7a748f16 100644 --- a/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java +++ b/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java @@ -42,6 +42,7 @@ import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.Callable; +import org.assertj.core.api.AbstractAssert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @@ -51,14 +52,8 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.ResolvableType.VariableResolver; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -86,31 +81,31 @@ public class ResolvableTypeTests { @Test public void noneReturnValues() throws Exception { ResolvableType none = ResolvableType.NONE; - assertThat(none.as(Object.class), equalTo(ResolvableType.NONE)); - assertThat(none.asCollection(), equalTo(ResolvableType.NONE)); - assertThat(none.asMap(), equalTo(ResolvableType.NONE)); - assertThat(none.getComponentType(), equalTo(ResolvableType.NONE)); - assertThat(none.getGeneric(0), equalTo(ResolvableType.NONE)); - assertThat(none.getGenerics().length, equalTo(0)); - assertThat(none.getInterfaces().length, equalTo(0)); - assertThat(none.getSuperType(), equalTo(ResolvableType.NONE)); - assertThat(none.getType(), equalTo(ResolvableType.EmptyType.INSTANCE)); - assertThat(none.hasGenerics(), equalTo(false)); - assertThat(none.isArray(), equalTo(false)); - assertThat(none.resolve(), nullValue()); - assertThat(none.resolve(String.class), equalTo((Class) String.class)); - assertThat(none.resolveGeneric(0), nullValue()); - assertThat(none.resolveGenerics().length, equalTo(0)); - assertThat(none.toString(), equalTo("?")); - assertThat(none.hasUnresolvableGenerics(), equalTo(false)); - assertThat(none.isAssignableFrom(ResolvableType.forClass(Object.class)), equalTo(false)); + assertThat(none.as(Object.class)).isEqualTo(ResolvableType.NONE); + assertThat(none.asCollection()).isEqualTo(ResolvableType.NONE); + assertThat(none.asMap()).isEqualTo(ResolvableType.NONE); + assertThat(none.getComponentType()).isEqualTo(ResolvableType.NONE); + assertThat(none.getGeneric(0)).isEqualTo(ResolvableType.NONE); + assertThat(none.getGenerics().length).isEqualTo(0); + assertThat(none.getInterfaces().length).isEqualTo(0); + assertThat(none.getSuperType()).isEqualTo(ResolvableType.NONE); + assertThat(none.getType()).isEqualTo(ResolvableType.EmptyType.INSTANCE); + assertThat(none.hasGenerics()).isEqualTo(false); + assertThat(none.isArray()).isEqualTo(false); + assertThat(none.resolve()).isNull(); + assertThat(none.resolve(String.class)).isEqualTo(String.class); + assertThat(none.resolveGeneric(0)).isNull(); + assertThat(none.resolveGenerics().length).isEqualTo(0); + assertThat(none.toString()).isEqualTo("?"); + assertThat(none.hasUnresolvableGenerics()).isEqualTo(false); + assertThat(none.isAssignableFrom(ResolvableType.forClass(Object.class))).isEqualTo(false); } @Test public void forClass() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class); - assertThat(type.getType(), equalTo((Type) ExtendsList.class)); - assertThat(type.getRawClass(), equalTo(ExtendsList.class)); + assertThat(type.getType()).isEqualTo(ExtendsList.class); + assertThat(type.getRawClass()).isEqualTo(ExtendsList.class); assertTrue(type.isAssignableFrom(ExtendsList.class)); assertFalse(type.isAssignableFrom(ArrayList.class)); } @@ -118,8 +113,8 @@ public class ResolvableTypeTests { @Test public void forClassWithNull() throws Exception { ResolvableType type = ResolvableType.forClass(null); - assertThat(type.getType(), equalTo((Type) Object.class)); - assertThat(type.getRawClass(), equalTo(Object.class)); + assertThat(type.getType()).isEqualTo(Object.class); + assertThat(type.getRawClass()).isEqualTo(Object.class); assertTrue(type.isAssignableFrom(Object.class)); assertTrue(type.isAssignableFrom(String.class)); } @@ -127,8 +122,8 @@ public class ResolvableTypeTests { @Test public void forRawClass() throws Exception { ResolvableType type = ResolvableType.forRawClass(ExtendsList.class); - assertThat(type.getType(), equalTo((Type) ExtendsList.class)); - assertThat(type.getRawClass(), equalTo(ExtendsList.class)); + assertThat(type.getType()).isEqualTo(ExtendsList.class); + assertThat(type.getRawClass()).isEqualTo(ExtendsList.class); assertTrue(type.isAssignableFrom(ExtendsList.class)); assertFalse(type.isAssignableFrom(ArrayList.class)); } @@ -136,8 +131,8 @@ public class ResolvableTypeTests { @Test public void forRawClassWithNull() throws Exception { ResolvableType type = ResolvableType.forRawClass(null); - assertThat(type.getType(), equalTo((Type) Object.class)); - assertThat(type.getRawClass(), equalTo(Object.class)); + assertThat(type.getType()).isEqualTo(Object.class); + assertThat(type.getRawClass()).isEqualTo(Object.class); assertTrue(type.isAssignableFrom(Object.class)); assertTrue(type.isAssignableFrom(String.class)); } @@ -152,44 +147,44 @@ public class ResolvableTypeTests { @Test public void forInstanceNoProvider() { ResolvableType type = ResolvableType.forInstance(new Object()); - assertThat(type.getType(), equalTo(Object.class)); - assertThat(type.resolve(), equalTo(Object.class)); + assertThat(type.getType()).isEqualTo(Object.class); + assertThat(type.resolve()).isEqualTo(Object.class); } @Test public void forInstanceProvider() { ResolvableType type = ResolvableType.forInstance(new MyGenericInterfaceType<>(String.class)); - assertThat(type.getRawClass(), equalTo(MyGenericInterfaceType.class)); - assertThat(type.getGeneric().resolve(), equalTo(String.class)); + assertThat(type.getRawClass()).isEqualTo(MyGenericInterfaceType.class); + assertThat(type.getGeneric().resolve()).isEqualTo(String.class); } @Test public void forInstanceProviderNull() { ResolvableType type = ResolvableType.forInstance(new MyGenericInterfaceType(null)); - assertThat(type.getType(), equalTo(MyGenericInterfaceType.class)); - assertThat(type.resolve(), equalTo(MyGenericInterfaceType.class)); + assertThat(type.getType()).isEqualTo(MyGenericInterfaceType.class); + assertThat(type.resolve()).isEqualTo(MyGenericInterfaceType.class); } @Test public void forField() throws Exception { Field field = Fields.class.getField("charSequenceList"); ResolvableType type = ResolvableType.forField(field); - assertThat(type.getType(), equalTo(field.getGenericType())); + assertThat(type.getType()).isEqualTo(field.getGenericType()); } @Test public void forPrivateField() throws Exception { Field field = Fields.class.getDeclaredField("privateField"); ResolvableType type = ResolvableType.forField(field); - assertThat(type.getType(), equalTo(field.getGenericType())); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.getSource(), sameInstance(field)); + assertThat(type.getType()).isEqualTo(field.getGenericType()); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.getSource()).isSameAs(field); Field field2 = Fields.class.getDeclaredField("otherPrivateField"); ResolvableType type2 = ResolvableType.forField(field2); - assertThat(type2.getType(), equalTo(field2.getGenericType())); - assertThat(type2.resolve(), equalTo((Class) List.class)); - assertThat(type2.getSource(), sameInstance(field2)); + assertThat(type2.getType()).isEqualTo(field2.getGenericType()); + assertThat(type2.resolve()).isEqualTo(List.class); + assertThat(type2.getSource()).isSameAs(field2); assertEquals(type, type2); assertEquals(type.hashCode(), type2.hashCode()); @@ -206,7 +201,7 @@ public class ResolvableTypeTests { public void forConstructorParameter() throws Exception { Constructor constructor = Constructors.class.getConstructor(List.class); ResolvableType type = ResolvableType.forConstructorParameter(constructor, 0); - assertThat(type.getType(), equalTo(constructor.getGenericParameterTypes()[0])); + assertThat(type.getType()).isEqualTo(constructor.getGenericParameterTypes()[0]); } @Test @@ -220,7 +215,7 @@ public class ResolvableTypeTests { public void forMethodParameterByIndex() throws Exception { Method method = Methods.class.getMethod("charSequenceParameter", List.class); ResolvableType type = ResolvableType.forMethodParameter(method, 0); - assertThat(type.getType(), equalTo(method.getGenericParameterTypes()[0])); + assertThat(type.getType()).isEqualTo(method.getGenericParameterTypes()[0]); } @Test @@ -235,7 +230,7 @@ public class ResolvableTypeTests { Method method = Methods.class.getMethod("charSequenceParameter", List.class); MethodParameter methodParameter = MethodParameter.forExecutable(method, 0); ResolvableType type = ResolvableType.forMethodParameter(methodParameter); - assertThat(type.getType(), equalTo(method.getGenericParameterTypes()[0])); + assertThat(type.getType()).isEqualTo(method.getGenericParameterTypes()[0]); } @Test @@ -244,9 +239,9 @@ public class ResolvableTypeTests { MethodParameter methodParameter = MethodParameter.forExecutable(method, 0); methodParameter.increaseNestingLevel(); ResolvableType type = ResolvableType.forMethodParameter(methodParameter); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) Byte.class)); - assertThat(type.getGeneric(1).resolve(), equalTo((Class) Long.class)); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.getGeneric(0).resolve()).isEqualTo(Byte.class); + assertThat(type.getGeneric(1).resolve()).isEqualTo(Long.class); } @Test @@ -256,9 +251,9 @@ public class ResolvableTypeTests { methodParameter.increaseNestingLevel(); methodParameter.setTypeIndexForCurrentLevel(0); ResolvableType type = ResolvableType.forMethodParameter(methodParameter); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); - assertThat(type.getGeneric(1).resolve(), equalTo((Class) Integer.class)); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.getGeneric(0).resolve()).isEqualTo(String.class); + assertThat(type.getGeneric(1).resolve()).isEqualTo(Integer.class); } @Test @@ -273,19 +268,19 @@ public class ResolvableTypeTests { Method method = Methods.class.getMethod("list1"); MethodParameter methodParameter = MethodParameter.forExecutable(method, -1); ResolvableType type = ResolvableType.forMethodParameter(methodParameter); - assertThat(((MethodParameter)type.getSource()).getMethod(), equalTo(method)); + assertThat(((MethodParameter)type.getSource()).getMethod()).isEqualTo(method); method = Methods.class.getMethod("list2"); methodParameter = MethodParameter.forExecutable(method, -1); type = ResolvableType.forMethodParameter(methodParameter); - assertThat(((MethodParameter)type.getSource()).getMethod(), equalTo(method)); + assertThat(((MethodParameter)type.getSource()).getMethod()).isEqualTo(method); } @Test public void forMethodReturn() throws Exception { Method method = Methods.class.getMethod("charSequenceReturn"); ResolvableType type = ResolvableType.forMethodReturnType(method); - assertThat(type.getType(), equalTo(method.getGenericReturnType())); + assertThat(type.getType()).isEqualTo(method.getGenericReturnType()); } @Test @@ -298,450 +293,449 @@ public class ResolvableTypeTests { @Test public void classType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("classType")); - assertThat(type.getType().getClass(), equalTo((Class) Class.class)); + assertThat(type.getType().getClass()).isEqualTo(Class.class); } @Test public void paramaterizedType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("parameterizedType")); - assertThat(type.getType(), instanceOf(ParameterizedType.class)); + assertThat(type.getType()).isInstanceOf(ParameterizedType.class); } @Test public void arrayClassType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("arrayClassType")); - assertThat(type.getType(), instanceOf(Class.class)); - assertThat(((Class) type.getType()).isArray(), equalTo(true)); + assertThat(type.getType()).isInstanceOf(Class.class); + assertThat(((Class) type.getType()).isArray()).isEqualTo(true); } @Test public void genericArrayType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); - assertThat(type.getType(), instanceOf(GenericArrayType.class)); + assertThat(type.getType()).isInstanceOf(GenericArrayType.class); } @Test public void wildcardType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("wildcardType")); - assertThat(type.getType(), instanceOf(ParameterizedType.class)); - assertThat(type.getGeneric().getType(), instanceOf(WildcardType.class)); + assertThat(type.getType()).isInstanceOf(ParameterizedType.class); + assertThat(type.getGeneric().getType()).isInstanceOf(WildcardType.class); } @Test public void typeVariableType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("typeVariableType")); - assertThat(type.getType(), instanceOf(TypeVariable.class)); + assertThat(type.getType()).isInstanceOf(TypeVariable.class); } @Test public void getComponentTypeForClassArray() throws Exception { Field field = Fields.class.getField("arrayClassType"); ResolvableType type = ResolvableType.forField(field); - assertThat(type.isArray(), equalTo(true)); - assertThat(type.getComponentType().getType(), - equalTo((Type) ((Class) field.getGenericType()).getComponentType())); + assertThat(type.isArray()).isEqualTo(true); + assertThat(type.getComponentType().getType()) + .isEqualTo(((Class) field.getGenericType()).getComponentType()); } @Test public void getComponentTypeForGenericArrayType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); - assertThat(type.isArray(), equalTo(true)); - assertThat(type.getComponentType().getType(), - equalTo(((GenericArrayType) type.getType()).getGenericComponentType())); + assertThat(type.isArray()).isEqualTo(true); + assertThat(type.getComponentType().getType()).isEqualTo( + ((GenericArrayType) type.getType()).getGenericComponentType()); } @Test public void getComponentTypeForVariableThatResolvesToGenericArray() throws Exception { ResolvableType type = ResolvableType.forClass(ListOfGenericArray.class).asCollection().getGeneric(); - assertThat(type.isArray(), equalTo(true)); - assertThat(type.getType(), instanceOf(TypeVariable.class)); - assertThat(type.getComponentType().getType().toString(), - equalTo("java.util.List")); + assertThat(type.isArray()).isEqualTo(true); + assertThat(type.getType()).isInstanceOf(TypeVariable.class); + assertThat(type.getComponentType().getType().toString()).isEqualTo( + "java.util.List"); } @Test public void getComponentTypeForNonArray() throws Exception { ResolvableType type = ResolvableType.forClass(String.class); - assertThat(type.isArray(), equalTo(false)); - assertThat(type.getComponentType(), equalTo(ResolvableType.NONE)); + assertThat(type.isArray()).isEqualTo(false); + assertThat(type.getComponentType()).isEqualTo(ResolvableType.NONE); } @Test public void asCollection() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).asCollection(); - assertThat(type.resolve(), equalTo((Class) Collection.class)); - assertThat(type.resolveGeneric(), equalTo((Class) CharSequence.class)); + assertThat(type.resolve()).isEqualTo(Collection.class); + assertThat(type.resolveGeneric()).isEqualTo(CharSequence.class); } @Test public void asMap() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsMap.class).asMap(); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.resolveGeneric(0), equalTo((Class) String.class)); - assertThat(type.resolveGeneric(1), equalTo((Class) Integer.class)); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.resolveGeneric(0)).isEqualTo(String.class); + assertThat(type.resolveGeneric(1)).isEqualTo(Integer.class); } @Test public void asFromInterface() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(List.class); - assertThat(type.getType().toString(), equalTo("java.util.List")); + assertThat(type.getType().toString()).isEqualTo("java.util.List"); } @Test public void asFromInheritedInterface() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(Collection.class); - assertThat(type.getType().toString(), equalTo("java.util.Collection")); + assertThat(type.getType().toString()).isEqualTo("java.util.Collection"); } @Test public void asFromSuperType() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(ArrayList.class); - assertThat(type.getType().toString(), equalTo("java.util.ArrayList")); + assertThat(type.getType().toString()).isEqualTo("java.util.ArrayList"); } @Test public void asFromInheritedSuperType() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(List.class); - assertThat(type.getType().toString(), equalTo("java.util.List")); + assertThat(type.getType().toString()).isEqualTo("java.util.List"); } @Test public void asNotFound() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(Map.class); - assertThat(type, sameInstance(ResolvableType.NONE)); + assertThat(type).isSameAs(ResolvableType.NONE); } @Test public void asSelf() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class); - assertThat(type.as(ExtendsList.class), equalTo(type)); + assertThat(type.as(ExtendsList.class)).isEqualTo(type); } @Test public void getSuperType() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class).getSuperType(); - assertThat(type.resolve(), equalTo((Class) ArrayList.class)); + assertThat(type.resolve()).isEqualTo(ArrayList.class); type = type.getSuperType(); - assertThat(type.resolve(), equalTo((Class) AbstractList.class)); + assertThat(type.resolve()).isEqualTo(AbstractList.class); type = type.getSuperType(); - assertThat(type.resolve(), equalTo((Class) AbstractCollection.class)); + assertThat(type.resolve()).isEqualTo(AbstractCollection.class); type = type.getSuperType(); - assertThat(type.resolve(), equalTo((Class) Object.class)); + assertThat(type.resolve()).isEqualTo(Object.class); } @Test public void getInterfaces() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class); - assertThat(type.getInterfaces().length, equalTo(0)); + assertThat(type.getInterfaces().length).isEqualTo(0); SortedSet interfaces = new TreeSet<>(); for (ResolvableType interfaceType : type.getSuperType().getInterfaces()) { interfaces.add(interfaceType.toString()); } - assertThat(interfaces.toString(), equalTo( + assertThat(interfaces.toString()).isEqualTo( "[" + "java.io.Serializable, " + "java.lang.Cloneable, " + "java.util.List, " + "java.util.RandomAccess" - + "]")); + + "]"); } @Test public void noSuperType() throws Exception { - assertThat(ResolvableType.forClass(Object.class).getSuperType(), - equalTo(ResolvableType.NONE)); + assertThat(ResolvableType.forClass(Object.class).getSuperType()) + .isEqualTo(ResolvableType.NONE); } @Test public void noInterfaces() throws Exception { - assertThat(ResolvableType.forClass(Object.class).getInterfaces().length, - equalTo(0)); + assertThat(ResolvableType.forClass(Object.class).getInterfaces()).isEmpty(); } @Test public void nested() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("nested")); type = type.getNested(2); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) Byte.class)); - assertThat(type.getGeneric(1).resolve(), equalTo((Class) Long.class)); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.getGeneric(0).resolve()).isEqualTo(Byte.class); + assertThat(type.getGeneric(1).resolve()).isEqualTo(Long.class); } @Test public void nestedWithIndexes() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("nested")); type = type.getNested(2, Collections.singletonMap(2, 0)); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); - assertThat(type.getGeneric(1).resolve(), equalTo((Class) Integer.class)); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.getGeneric(0).resolve()).isEqualTo(String.class); + assertThat(type.getGeneric(1).resolve()).isEqualTo(Integer.class); } @Test public void nestedWithArray() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); type = type.getNested(2); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.resolveGeneric(), equalTo((Class) String.class)); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.resolveGeneric()).isEqualTo(String.class); } @Test public void getGeneric() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringList")); - assertThat(type.getGeneric().getType(), equalTo((Type) String.class)); + assertThat(type.getGeneric().getType()).isEqualTo(String.class); } @Test public void getGenericByIndex() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringIntegerMultiValueMap")); - assertThat(type.getGeneric(0).getType(), equalTo((Type) String.class)); - assertThat(type.getGeneric(1).getType(), equalTo((Type) Integer.class)); + assertThat(type.getGeneric(0).getType()).isEqualTo(String.class); + assertThat(type.getGeneric(1).getType()).isEqualTo(Integer.class); } @Test public void getGenericOfGeneric() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList")); - assertThat(type.getGeneric().getType().toString(), equalTo("java.util.List")); - assertThat(type.getGeneric().getGeneric().getType(), equalTo((Type) String.class)); + assertThat(type.getGeneric().getType().toString()).isEqualTo("java.util.List"); + assertThat(type.getGeneric().getGeneric().getType()).isEqualTo(String.class); } @Test public void genericOfGenericWithAs() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList")).asCollection(); - assertThat(type.toString(), equalTo("java.util.Collection>")); - assertThat(type.getGeneric().asCollection().toString(), equalTo("java.util.Collection")); + assertThat(type.toString()).isEqualTo("java.util.Collection>"); + assertThat(type.getGeneric().asCollection().toString()).isEqualTo("java.util.Collection"); } @Test public void getGenericOfGenericByIndexes() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList")); - assertThat(type.getGeneric(0, 0).getType(), equalTo((Type) String.class)); + assertThat(type.getGeneric(0, 0).getType()).isEqualTo(String.class); } @Test public void getGenericOutOfBounds() throws Exception { ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class); - assertThat(type.getGeneric(0), not(equalTo(ResolvableType.NONE))); - assertThat(type.getGeneric(1), equalTo(ResolvableType.NONE)); - assertThat(type.getGeneric(0, 1), equalTo(ResolvableType.NONE)); + assertThat(type.getGeneric(0)).isNotEqualTo(ResolvableType.NONE); + assertThat(type.getGeneric(1)).isEqualTo(ResolvableType.NONE); + assertThat(type.getGeneric(0, 1)).isEqualTo(ResolvableType.NONE); } @Test public void hasGenerics() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class); - assertThat(type.hasGenerics(), equalTo(false)); - assertThat(type.asCollection().hasGenerics(), equalTo(true)); + assertThat(type.hasGenerics()).isEqualTo(false); + assertThat(type.asCollection().hasGenerics()).isEqualTo(true); } @Test public void getGenericsFromParameterizedType() throws Exception { ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class); ResolvableType[] generics = type.getGenerics(); - assertThat(generics.length, equalTo(1)); - assertThat(generics[0].resolve(), equalTo((Class) CharSequence.class)); + assertThat(generics.length).isEqualTo(1); + assertThat(generics[0].resolve()).isEqualTo(CharSequence.class); } @Test public void getGenericsFromClass() throws Exception { ResolvableType type = ResolvableType.forClass(List.class); ResolvableType[] generics = type.getGenerics(); - assertThat(generics.length, equalTo(1)); - assertThat(generics[0].getType().toString(), equalTo("E")); + assertThat(generics.length).isEqualTo(1); + assertThat(generics[0].getType().toString()).isEqualTo("E"); } @Test public void noGetGenerics() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class); ResolvableType[] generics = type.getGenerics(); - assertThat(generics.length, equalTo(0)); + assertThat(generics.length).isEqualTo(0); } @Test public void getResolvedGenerics() throws Exception { ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class); Class[] generics = type.resolveGenerics(); - assertThat(generics.length, equalTo(1)); - assertThat(generics[0], equalTo((Class) CharSequence.class)); + assertThat(generics.length).isEqualTo(1); + assertThat(generics[0]).isEqualTo(CharSequence.class); } @Test public void resolveClassType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("classType")); - assertThat(type.resolve(), equalTo((Class) List.class)); + assertThat(type.resolve()).isEqualTo(List.class); } @Test public void resolveParameterizedType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("parameterizedType")); - assertThat(type.resolve(), equalTo((Class) List.class)); + assertThat(type.resolve()).isEqualTo(List.class); } @Test public void resolveArrayClassType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("arrayClassType")); - assertThat(type.resolve(), equalTo((Class) List[].class)); + assertThat(type.resolve()).isEqualTo(List[].class); } @Test public void resolveGenericArrayType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); - assertThat(type.resolve(), equalTo((Class) List[].class)); - assertThat(type.getComponentType().resolve(), equalTo((Class) List.class)); - assertThat(type.getComponentType().getGeneric().resolve(), equalTo((Class) String.class)); + assertThat(type.resolve()).isEqualTo(List[].class); + assertThat(type.getComponentType().resolve()).isEqualTo(List.class); + assertThat(type.getComponentType().getGeneric().resolve()).isEqualTo(String.class); } @Test public void resolveGenericMultiArrayType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("genericMultiArrayType")); - assertThat(type.resolve(), equalTo((Class) List[][][].class)); - assertThat(type.getComponentType().resolve(), equalTo((Class) List[][].class)); + assertThat(type.resolve()).isEqualTo(List[][][].class); + assertThat(type.getComponentType().resolve()).isEqualTo(List[][].class); } @Test public void resolveGenericArrayFromGeneric() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringArrayList")); ResolvableType generic = type.asCollection().getGeneric(); - assertThat(generic.getType().toString(), equalTo("E")); - assertThat(generic.isArray(), equalTo(true)); - assertThat(generic.resolve(), equalTo((Class) String[].class)); + assertThat(generic.getType().toString()).isEqualTo("E"); + assertThat(generic.isArray()).isEqualTo(true); + assertThat(generic.resolve()).isEqualTo(String[].class); } @Test public void resolveVariableGenericArray() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("variableTypeGenericArray"), TypedFields.class); - assertThat(type.getType().toString(), equalTo("T[]")); - assertThat(type.isArray(), equalTo(true)); - assertThat(type.resolve(), equalTo((Class) String[].class)); + assertThat(type.getType().toString()).isEqualTo("T[]"); + assertThat(type.isArray()).isEqualTo(true); + assertThat(type.resolve()).isEqualTo(String[].class); } @Test public void resolveVariableGenericArrayUnknown() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("variableTypeGenericArray")); - assertThat(type.getType().toString(), equalTo("T[]")); - assertThat(type.isArray(), equalTo(true)); - assertThat(type.resolve(), nullValue()); + assertThat(type.getType().toString()).isEqualTo("T[]"); + assertThat(type.isArray()).isEqualTo(true); + assertThat(type.resolve()).isNull(); } @Test public void resolveVariableGenericArrayUnknownWithFallback() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("variableTypeGenericArray")); - assertThat(type.getType().toString(), equalTo("T[]")); - assertThat(type.isArray(), equalTo(true)); - assertThat(type.toClass(), equalTo((Class) Object.class)); + assertThat(type.getType().toString()).isEqualTo("T[]"); + assertThat(type.isArray()).isEqualTo(true); + assertThat(type.toClass()).isEqualTo(Object.class); } @Test public void resolveWildcardTypeUpperBounds() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("wildcardType")); - assertThat(type.getGeneric().resolve(), equalTo((Class) Number.class)); + assertThat(type.getGeneric().resolve()).isEqualTo(Number.class); } @Test public void resolveWildcardLowerBounds() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("wildcardSuperType")); - assertThat(type.getGeneric().resolve(), equalTo((Class) Number.class)); + assertThat(type.getGeneric().resolve()).isEqualTo(Number.class); } @Test public void resolveVariableFromFieldType() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringList")); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric().resolve(), equalTo((Class) String.class)); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.getGeneric().resolve()).isEqualTo(String.class); } @Test public void resolveVariableFromFieldTypeUnknown() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("parameterizedType")); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric().resolve(), nullValue()); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.getGeneric().resolve()).isNull(); } @Test public void resolveVariableFromInheritedField() throws Exception { ResolvableType type = ResolvableType.forField( Fields.class.getField("stringIntegerMultiValueMap")).as(Map.class); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); - assertThat(type.getGeneric(1).resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric(1, 0).resolve(), equalTo((Class) Integer.class)); + assertThat(type.getGeneric(0).resolve()).isEqualTo(String.class); + assertThat(type.getGeneric(1).resolve()).isEqualTo(List.class); + assertThat(type.getGeneric(1, 0).resolve()).isEqualTo(Integer.class); } @Test public void resolveVariableFromInheritedFieldSwitched() throws Exception { ResolvableType type = ResolvableType.forField( Fields.class.getField("stringIntegerMultiValueMapSwitched")).as(Map.class); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); - assertThat(type.getGeneric(1).resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric(1, 0).resolve(), equalTo((Class) Integer.class)); + assertThat(type.getGeneric(0).resolve()).isEqualTo(String.class); + assertThat(type.getGeneric(1).resolve()).isEqualTo(List.class); + assertThat(type.getGeneric(1, 0).resolve()).isEqualTo(Integer.class); } @Test public void doesResolveFromOuterOwner() throws Exception { ResolvableType type = ResolvableType.forField( Fields.class.getField("listOfListOfUnknown")).as(Collection.class); - assertThat(type.getGeneric(0).resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric(0).as(Collection.class).getGeneric(0).as(Collection.class).resolve(), nullValue()); + assertThat(type.getGeneric(0).resolve()).isEqualTo(List.class); + assertThat(type.getGeneric(0).as(Collection.class).getGeneric(0).as(Collection.class).resolve()).isNull(); } @Test public void resolveBoundedTypeVariableResult() throws Exception { ResolvableType type = ResolvableType.forMethodReturnType(Methods.class.getMethod("boundedTypeVaraibleResult")); - assertThat(type.resolve(), equalTo((Class) CharSequence.class)); + assertThat(type.resolve()).isEqualTo(CharSequence.class); } @Test public void resolveVariableNotFound() throws Exception { ResolvableType type = ResolvableType.forMethodReturnType(Methods.class.getMethod("typedReturn")); - assertThat(type.resolve(), nullValue()); + assertThat(type.resolve()).isNull(); } @Test public void resolveTypeVaraibleFromMethodReturn() throws Exception { ResolvableType type = ResolvableType.forMethodReturnType(Methods.class.getMethod("typedReturn")); - assertThat(type.resolve(), nullValue()); + assertThat(type.resolve()).isNull(); } @Test public void resolveTypeVaraibleFromMethodReturnWithInstanceClass() throws Exception { ResolvableType type = ResolvableType.forMethodReturnType( Methods.class.getMethod("typedReturn"), TypedMethods.class); - assertThat(type.resolve(), equalTo((Class) String.class)); + assertThat(type.resolve()).isEqualTo(String.class); } @Test public void resolveTypeVaraibleFromSimpleInterfaceType() { ResolvableType type = ResolvableType.forClass( MySimpleInterfaceType.class).as(MyInterfaceType.class); - assertThat(type.resolveGeneric(), equalTo((Class) String.class)); + assertThat(type.resolveGeneric()).isEqualTo(String.class); } @Test public void resolveTypeVaraibleFromSimpleCollectionInterfaceType() { ResolvableType type = ResolvableType.forClass( MyCollectionInterfaceType.class).as(MyInterfaceType.class); - assertThat(type.resolveGeneric(), equalTo((Class) Collection.class)); - assertThat(type.resolveGeneric(0, 0), equalTo((Class) String.class)); + assertThat(type.resolveGeneric()).isEqualTo(Collection.class); + assertThat(type.resolveGeneric(0, 0)).isEqualTo(String.class); } @Test public void resolveTypeVaraibleFromSimpleSuperclassType() { ResolvableType type = ResolvableType.forClass( MySimpleSuperclassType.class).as(MySuperclassType.class); - assertThat(type.resolveGeneric(), equalTo((Class) String.class)); + assertThat(type.resolveGeneric()).isEqualTo(String.class); } @Test public void resolveTypeVaraibleFromSimpleCollectionSuperclassType() { ResolvableType type = ResolvableType.forClass( MyCollectionSuperclassType.class).as(MySuperclassType.class); - assertThat(type.resolveGeneric(), equalTo((Class) Collection.class)); - assertThat(type.resolveGeneric(0, 0), equalTo((Class) String.class)); + assertThat(type.resolveGeneric()).isEqualTo(Collection.class); + assertThat(type.resolveGeneric(0, 0)).isEqualTo(String.class); } @Test public void resolveTypeVariableFromFieldTypeWithImplementsClass() throws Exception { ResolvableType type = ResolvableType.forField( Fields.class.getField("parameterizedType"), TypedFields.class); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric().resolve(), equalTo((Class) String.class)); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.getGeneric().resolve()).isEqualTo(String.class); } @Test @@ -750,40 +744,40 @@ public class ResolvableTypeTests { Fields.class, Integer.class); ResolvableType type = ResolvableType.forField( Fields.class.getField("parameterizedType"), implementationType); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.getGeneric().resolve(), equalTo((Class) Integer.class)); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.getGeneric().resolve()).isEqualTo(Integer.class); } @Test public void resolveTypeVariableFromSuperType() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsList.class); - assertThat(type.resolve(), equalTo((Class) ExtendsList.class)); - assertThat(type.asCollection().resolveGeneric(), - equalTo((Class) CharSequence.class)); + assertThat(type.resolve()).isEqualTo(ExtendsList.class); + assertThat(type.asCollection().resolveGeneric()) + .isEqualTo(CharSequence.class); } @Test public void resolveTypeVariableFromClassWithImplementsClass() throws Exception { ResolvableType type = ResolvableType.forClass( MySuperclassType.class, MyCollectionSuperclassType.class); - assertThat(type.resolveGeneric(), equalTo((Class) Collection.class)); - assertThat(type.resolveGeneric(0, 0), equalTo((Class) String.class)); + assertThat(type.resolveGeneric()).isEqualTo(Collection.class); + assertThat(type.resolveGeneric(0, 0)).isEqualTo(String.class); } @Test public void resolveTypeVariableFromConstructorParameter() throws Exception { Constructor constructor = Constructors.class.getConstructor(List.class); ResolvableType type = ResolvableType.forConstructorParameter(constructor, 0); - assertThat(type.resolve(), equalTo((Class) List.class)); - assertThat(type.resolveGeneric(0), equalTo((Class) CharSequence.class)); + assertThat(type.resolve()).isEqualTo(List.class); + assertThat(type.resolveGeneric(0)).isEqualTo(CharSequence.class); } @Test public void resolveUnknownTypeVariableFromConstructorParameter() throws Exception { Constructor constructor = Constructors.class.getConstructor(Map.class); ResolvableType type = ResolvableType.forConstructorParameter(constructor, 0); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.resolveGeneric(0), nullValue()); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.resolveGeneric(0)).isNull(); } @Test @@ -791,24 +785,24 @@ public class ResolvableTypeTests { Constructor constructor = Constructors.class.getConstructor(Map.class); ResolvableType type = ResolvableType.forConstructorParameter( constructor, 0, TypedConstructors.class); - assertThat(type.resolve(), equalTo((Class) Map.class)); - assertThat(type.resolveGeneric(0), equalTo((Class) String.class)); + assertThat(type.resolve()).isEqualTo(Map.class); + assertThat(type.resolveGeneric(0)).isEqualTo(String.class); } @Test public void resolveTypeVariableFromMethodParameter() throws Exception { Method method = Methods.class.getMethod("typedParameter", Object.class); ResolvableType type = ResolvableType.forMethodParameter(method, 0); - assertThat(type.resolve(), nullValue()); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isNull(); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test public void resolveTypeVariableFromMethodParameterWithImplementsClass() throws Exception { Method method = Methods.class.getMethod("typedParameter", Object.class); ResolvableType type = ResolvableType.forMethodParameter(method, 0, TypedMethods.class); - assertThat(type.resolve(), equalTo((Class) String.class)); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isEqualTo(String.class); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test @@ -816,8 +810,8 @@ public class ResolvableTypeTests { Method method = Methods.class.getMethod("typedParameter", Object.class); MethodParameter methodParameter = MethodParameter.forExecutable(method, 0); ResolvableType type = ResolvableType.forMethodParameter(methodParameter); - assertThat(type.resolve(), nullValue()); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isNull(); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test @@ -826,8 +820,8 @@ public class ResolvableTypeTests { MethodParameter methodParameter = MethodParameter.forExecutable(method, 0); methodParameter.setContainingClass(TypedMethods.class); ResolvableType type = ResolvableType.forMethodParameter(methodParameter); - assertThat(type.resolve(), equalTo((Class) String.class)); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isEqualTo(String.class); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test @@ -836,32 +830,32 @@ public class ResolvableTypeTests { MethodParameter methodParameter = MethodParameter.forExecutable(method, 0); ResolvableType implementationType = ResolvableType.forClassWithGenerics(Methods.class, Integer.class); ResolvableType type = ResolvableType.forMethodParameter(methodParameter, implementationType); - assertThat(type.resolve(), equalTo((Class) Integer.class)); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isEqualTo(Integer.class); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test public void resolveTypeVariableFromMethodReturn() throws Exception { Method method = Methods.class.getMethod("typedReturn"); ResolvableType type = ResolvableType.forMethodReturnType(method); - assertThat(type.resolve(), nullValue()); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isNull(); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test public void resolveTypeVariableFromMethodReturnWithImplementsClass() throws Exception { Method method = Methods.class.getMethod("typedReturn"); ResolvableType type = ResolvableType.forMethodReturnType(method, TypedMethods.class); - assertThat(type.resolve(), equalTo((Class) String.class)); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isEqualTo(String.class); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test public void resolveTypeVariableFromType() throws Exception { Type sourceType = Methods.class.getMethod("typedReturn").getGenericReturnType(); ResolvableType type = ResolvableType.forType(sourceType); - assertThat(type.resolve(), nullValue()); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isNull(); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test @@ -869,8 +863,8 @@ public class ResolvableTypeTests { Type sourceType = Methods.class.getMethod("typedReturn").getGenericReturnType(); ResolvableType type = ResolvableType.forType( sourceType, ResolvableType.forClass(TypedMethods.class).as(Methods.class).asVariableResolver()); - assertThat(type.resolve(), equalTo((Class) String.class)); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isEqualTo(String.class); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test @@ -885,19 +879,19 @@ public class ResolvableTypeTests { ResolvableType parameterized = ResolvableType.forType( Fields.class.getField("parameterizedType").getGenericType(), variableResolver); - assertThat(variable.resolve(), equalTo((Class) Long.class)); - assertThat(parameterized.resolve(), equalTo((Class) List.class)); - assertThat(parameterized.resolveGeneric(), equalTo((Class) Long.class)); + assertThat(variable.resolve()).isEqualTo(Long.class); + assertThat(parameterized.resolve()).isEqualTo(List.class); + assertThat(parameterized.resolveGeneric()).isEqualTo(Long.class); verify(variableResolver, atLeastOnce()).resolveVariable(this.typeVariableCaptor.capture()); - assertThat(this.typeVariableCaptor.getValue().getName(), equalTo("T")); + assertThat(this.typeVariableCaptor.getValue().getName()).isEqualTo("T"); } @Test public void resolveTypeVariableFromReflectiveParameterizedTypeReference() throws Exception { Type sourceType = Methods.class.getMethod("typedReturn").getGenericReturnType(); ResolvableType type = ResolvableType.forType(ParameterizedTypeReference.forType(sourceType)); - assertThat(type.resolve(), nullValue()); - assertThat(type.getType().toString(), equalTo("T")); + assertThat(type.resolve()).isNull(); + assertThat(type.getType().toString()).isEqualTo("T"); } @Test @@ -910,29 +904,29 @@ public class ResolvableTypeTests { @Test public void toStrings() throws Exception { - assertThat(ResolvableType.NONE.toString(), equalTo("?")); + assertThat(ResolvableType.NONE.toString()).isEqualTo("?"); - assertFieldToStringValue("classType", "java.util.List"); - assertFieldToStringValue("typeVariableType", "?"); - assertFieldToStringValue("parameterizedType", "java.util.List"); - assertFieldToStringValue("arrayClassType", "java.util.List[]"); - assertFieldToStringValue("genericArrayType", "java.util.List[]"); - assertFieldToStringValue("genericMultiArrayType", "java.util.List[][][]"); - assertFieldToStringValue("wildcardType", "java.util.List"); - assertFieldToStringValue("wildcardSuperType", "java.util.List"); - assertFieldToStringValue("charSequenceList", "java.util.List"); - assertFieldToStringValue("stringList", "java.util.List"); - assertFieldToStringValue("stringListList", "java.util.List>"); - assertFieldToStringValue("stringArrayList", "java.util.List"); - assertFieldToStringValue("stringIntegerMultiValueMap", "org.springframework.util.MultiValueMap"); - assertFieldToStringValue("stringIntegerMultiValueMapSwitched", VariableNameSwitch.class.getName() + ""); - assertFieldToStringValue("listOfListOfUnknown", "java.util.List>"); + assertThat(forField("classType")).hasToString("java.util.List"); + assertThat(forField("typeVariableType")).hasToString("?"); + assertThat(forField("parameterizedType")).hasToString("java.util.List"); + assertThat(forField("arrayClassType")).hasToString("java.util.List[]"); + assertThat(forField("genericArrayType")).hasToString("java.util.List[]"); + assertThat(forField("genericMultiArrayType")).hasToString("java.util.List[][][]"); + assertThat(forField("wildcardType")).hasToString("java.util.List"); + assertThat(forField("wildcardSuperType")).hasToString("java.util.List"); + assertThat(forField("charSequenceList")).hasToString("java.util.List"); + assertThat(forField("stringList")).hasToString("java.util.List"); + assertThat(forField("stringListList")).hasToString("java.util.List>"); + assertThat(forField("stringArrayList")).hasToString("java.util.List"); + assertThat(forField("stringIntegerMultiValueMap")).hasToString("org.springframework.util.MultiValueMap"); + assertThat(forField("stringIntegerMultiValueMapSwitched")).hasToString(VariableNameSwitch.class.getName() + ""); + assertThat(forField("listOfListOfUnknown")).hasToString("java.util.List>"); - assertTypedFieldToStringValue("typeVariableType", "java.lang.String"); - assertTypedFieldToStringValue("parameterizedType", "java.util.List"); + assertThat(forTypedField("typeVariableType")).hasToString("java.lang.String"); + assertThat(forTypedField("parameterizedType")).hasToString("java.util.List"); - assertThat(ResolvableType.forClass(ListOfGenericArray.class).toString(), equalTo(ListOfGenericArray.class.getName())); - assertThat(ResolvableType.forClass(List.class, ListOfGenericArray.class).toString(), equalTo("java.util.List[]>")); + assertThat(ResolvableType.forClass(ListOfGenericArray.class).toString()).isEqualTo(ListOfGenericArray.class.getName()); + assertThat(ResolvableType.forClass(List.class, ListOfGenericArray.class).toString()).isEqualTo("java.util.List[]>"); } @Test @@ -942,29 +936,29 @@ public class ResolvableTypeTests { Field field = Fields.class.getField("charSequenceList"); Method method = Methods.class.getMethod("charSequenceParameter", List.class); MethodParameter methodParameter = MethodParameter.forExecutable(method, 0); - assertThat(ResolvableType.forField(basicField).getSource(), equalTo((Object) basicField)); - assertThat(ResolvableType.forField(field).getSource(), equalTo((Object) field)); - assertThat(ResolvableType.forMethodParameter(methodParameter).getSource(), equalTo((Object) methodParameter)); - assertThat(ResolvableType.forMethodParameter(method, 0).getSource(), equalTo((Object) methodParameter)); - assertThat(ResolvableType.forClass(classType).getSource(), equalTo((Object) classType)); - assertThat(ResolvableType.forClass(classType).getSuperType().getSource(), equalTo((Object) classType.getGenericSuperclass())); + assertThat(ResolvableType.forField(basicField).getSource()).isEqualTo(basicField); + assertThat(ResolvableType.forField(field).getSource()).isEqualTo(field); + assertThat(ResolvableType.forMethodParameter(methodParameter).getSource()).isEqualTo(methodParameter); + assertThat(ResolvableType.forMethodParameter(method, 0).getSource()).isEqualTo(methodParameter); + assertThat(ResolvableType.forClass(classType).getSource()).isEqualTo(classType); + assertThat(ResolvableType.forClass(classType).getSuperType().getSource()).isEqualTo(classType.getGenericSuperclass()); } @Test public void resolveFromOuterClass() throws Exception { Field field = EnclosedInParameterizedType.InnerTyped.class.getField("field"); ResolvableType type = ResolvableType.forField(field, TypedEnclosedInParameterizedType.TypedInnerTyped.class); - assertThat(type.resolve(), equalTo((Type) Integer.class)); + assertThat(type.resolve()).isEqualTo(Integer.class); } @Test public void resolveFromClassWithGenerics() throws Exception { ResolvableType type = ResolvableType.forClassWithGenerics(List.class, ResolvableType.forClassWithGenerics(List.class, String.class)); - assertThat(type.asCollection().toString(), equalTo("java.util.Collection>")); - assertThat(type.asCollection().getGeneric().toString(), equalTo("java.util.List")); - assertThat(type.asCollection().getGeneric().asCollection().toString(), equalTo("java.util.Collection")); - assertThat(type.toString(), equalTo("java.util.List>")); - assertThat(type.asCollection().getGeneric().getGeneric().resolve(), equalTo((Type) String.class)); + assertThat(type.asCollection().toString()).isEqualTo("java.util.Collection>"); + assertThat(type.asCollection().getGeneric().toString()).isEqualTo("java.util.List"); + assertThat(type.asCollection().getGeneric().asCollection().toString()).isEqualTo("java.util.Collection"); + assertThat(type.toString()).isEqualTo("java.util.List>"); + assertThat(type.asCollection().getGeneric().getGeneric().resolve()).isEqualTo(String.class); } @Test @@ -977,8 +971,8 @@ public class ResolvableTypeTests { @Test public void isAssignableFromForNone() throws Exception { ResolvableType objectType = ResolvableType.forClass(Object.class); - assertThat(objectType.isAssignableFrom(ResolvableType.NONE), equalTo(false)); - assertThat(ResolvableType.NONE.isAssignableFrom(objectType), equalTo(false)); + assertThat(objectType.isAssignableFrom(ResolvableType.NONE)).isEqualTo(false); + assertThat(ResolvableType.NONE.isAssignableFrom(objectType)).isEqualTo(false); } @Test @@ -987,9 +981,9 @@ public class ResolvableTypeTests { ResolvableType charSequenceType = ResolvableType.forClass(CharSequence.class); ResolvableType stringType = ResolvableType.forClass(String.class); - assertAssignable(objectType, objectType, charSequenceType, stringType).equalTo(true, true, true); - assertAssignable(charSequenceType, objectType, charSequenceType, stringType).equalTo(false, true, true); - assertAssignable(stringType, objectType, charSequenceType, stringType).equalTo(false, false, true); + assertThatResolvableType(objectType).isAssignableFrom(objectType, charSequenceType, stringType); + assertThatResolvableType(charSequenceType).isAssignableFrom(charSequenceType, stringType).isNotAssignableFrom(objectType); + assertThatResolvableType(stringType).isAssignableFrom(stringType).isNotAssignableFrom(objectType, charSequenceType); assertTrue(objectType.isAssignableFrom(String.class)); assertTrue(objectType.isAssignableFrom(StringBuilder.class)); @@ -1010,9 +1004,9 @@ public class ResolvableTypeTests { public void isAssignableFromCannotBeResolved() throws Exception { ResolvableType objectType = ResolvableType.forClass(Object.class); ResolvableType unresolvableVariable = ResolvableType.forField(AssignmentBase.class.getField("o")); - assertThat(unresolvableVariable.resolve(), nullValue()); - assertAssignable(objectType, unresolvableVariable).equalTo(true); - assertAssignable(unresolvableVariable, objectType).equalTo(true); + assertThat(unresolvableVariable.resolve()).isNull(); + assertThatResolvableType(objectType).isAssignableFrom(unresolvableVariable); + assertThatResolvableType(unresolvableVariable).isAssignableFrom(objectType); } @Test @@ -1025,17 +1019,17 @@ public class ResolvableTypeTests { ResolvableType charSequenceVariable = ResolvableType.forField(AssignmentBase.class.getField("c"), Assignment.class); ResolvableType stringVariable = ResolvableType.forField(AssignmentBase.class.getField("s"), Assignment.class); - assertAssignable(objectType, objectVariable, charSequenceVariable, stringVariable).equalTo(true, true, true); - assertAssignable(charSequenceType, objectVariable, charSequenceVariable, stringVariable).equalTo(false, true, true); - assertAssignable(stringType, objectVariable, charSequenceVariable, stringVariable).equalTo(false, false, true); + assertThatResolvableType(objectType).isAssignableFrom(objectVariable, charSequenceVariable, stringVariable); + assertThatResolvableType(charSequenceType).isAssignableFrom(charSequenceVariable, stringVariable).isNotAssignableFrom(objectVariable); + assertThatResolvableType(stringType).isAssignableFrom(stringVariable).isNotAssignableFrom(objectVariable, charSequenceVariable); - assertAssignable(objectVariable, objectType, charSequenceType, stringType).equalTo(true, true, true); - assertAssignable(charSequenceVariable, objectType, charSequenceType, stringType).equalTo(false, true, true); - assertAssignable(stringVariable, objectType, charSequenceType, stringType).equalTo(false, false, true); + assertThatResolvableType(objectVariable).isAssignableFrom(objectType, charSequenceType, stringType); + assertThatResolvableType(charSequenceVariable).isAssignableFrom(charSequenceType, stringType).isNotAssignableFrom(objectType); + assertThatResolvableType(stringVariable).isAssignableFrom(stringType).isNotAssignableFrom(objectType, charSequenceType); - assertAssignable(objectVariable, objectVariable, charSequenceVariable, stringVariable).equalTo(true, true, true); - assertAssignable(charSequenceVariable, objectVariable, charSequenceVariable, stringVariable).equalTo(false, true, true); - assertAssignable(stringVariable, objectVariable, charSequenceVariable, stringVariable).equalTo(false, false, true); + assertThatResolvableType(objectVariable).isAssignableFrom(objectVariable, charSequenceVariable, stringVariable); + assertThatResolvableType(charSequenceVariable).isAssignableFrom(charSequenceVariable, stringVariable).isNotAssignableFrom(objectVariable); + assertThatResolvableType(stringVariable).isAssignableFrom(stringVariable).isNotAssignableFrom(objectVariable, charSequenceVariable); } @Test @@ -1043,9 +1037,9 @@ public class ResolvableTypeTests { ResolvableType objectList = ResolvableType.forField(AssignmentBase.class.getField("listo"), Assignment.class); ResolvableType stringList = ResolvableType.forField(AssignmentBase.class.getField("lists"), Assignment.class); - assertAssignable(stringList, objectList).equalTo(false); - assertAssignable(objectList, stringList).equalTo(false); - assertAssignable(stringList, stringList).equalTo(true); + assertThatResolvableType(stringList).isNotAssignableFrom(objectList); + assertThatResolvableType(objectList).isNotAssignableFrom(stringList); + assertThatResolvableType(stringList).isAssignableFrom(stringList); } @Test @@ -1071,15 +1065,15 @@ public class ResolvableTypeTests { ResolvableType extendsCharSequenceList = ResolvableType.forField(AssignmentBase.class.getField("listxc"), Assignment.class); ResolvableType extendsStringList = ResolvableType.forField(AssignmentBase.class.getField("listxs"), Assignment.class); - assertAssignable(objectList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, false); - assertAssignable(charSequenceList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, false); - assertAssignable(stringList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, false); - assertAssignable(extendsObjectList, objectList, charSequenceList, stringList).equalTo(true, true, true); - assertAssignable(extendsObjectList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(true, true, true); - assertAssignable(extendsCharSequenceList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, true, true); - assertAssignable(extendsCharSequenceList, objectList, charSequenceList, stringList).equalTo(false, true, true); - assertAssignable(extendsStringList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, true); - assertAssignable(extendsStringList, objectList, charSequenceList, stringList).equalTo(false, false, true); + assertThatResolvableType(objectList).isNotAssignableFrom(extendsObjectList, extendsCharSequenceList, extendsStringList); + assertThatResolvableType(charSequenceList).isNotAssignableFrom(extendsObjectList, extendsCharSequenceList, extendsStringList); + assertThatResolvableType(stringList).isNotAssignableFrom(extendsObjectList, extendsCharSequenceList, extendsStringList); + assertThatResolvableType(extendsObjectList).isAssignableFrom(objectList, charSequenceList, stringList); + assertThatResolvableType(extendsObjectList).isAssignableFrom(extendsObjectList, extendsCharSequenceList, extendsStringList); + assertThatResolvableType(extendsCharSequenceList).isAssignableFrom(extendsCharSequenceList, extendsStringList).isNotAssignableFrom(extendsObjectList); + assertThatResolvableType(extendsCharSequenceList).isAssignableFrom(charSequenceList, stringList).isNotAssignableFrom(objectList); + assertThatResolvableType(extendsStringList).isAssignableFrom(extendsStringList).isNotAssignableFrom(extendsObjectList, extendsCharSequenceList); + assertThatResolvableType(extendsStringList).isAssignableFrom(stringList).isNotAssignableFrom(objectList, charSequenceList); } @Test @@ -1090,16 +1084,11 @@ public class ResolvableTypeTests { ResolvableType extendsCharSequenceList = ResolvableType.forField(AssignmentBase.class.getField("listxc"), Assignment.class); ResolvableType extendsStringList = ResolvableType.forField(AssignmentBase.class.getField("listxs"), Assignment.class); - assertAssignable(extendsCharSequenceCollection, charSequenceCollection, charSequenceList, extendsCharSequenceList, extendsStringList) - .equalTo(true, true, true, true); - assertAssignable(charSequenceCollection, charSequenceList, extendsCharSequenceList, extendsStringList) - .equalTo(true, false, false); - assertAssignable(charSequenceList, extendsCharSequenceCollection, charSequenceCollection) - .equalTo(false, false); - assertAssignable(extendsCharSequenceList, extendsCharSequenceCollection, charSequenceCollection) - .equalTo(false, false); - assertAssignable(extendsStringList, charSequenceCollection, charSequenceList, extendsCharSequenceList) - .equalTo(false, false, false); + assertThatResolvableType(extendsCharSequenceCollection).isAssignableFrom(charSequenceCollection, charSequenceList, extendsCharSequenceList, extendsStringList); + assertThatResolvableType(charSequenceCollection).isAssignableFrom(charSequenceList).isNotAssignableFrom(extendsCharSequenceList, extendsStringList); + assertThatResolvableType(charSequenceList).isNotAssignableFrom(extendsCharSequenceCollection, charSequenceCollection); + assertThatResolvableType(extendsCharSequenceList).isNotAssignableFrom(extendsCharSequenceCollection, charSequenceCollection); + assertThatResolvableType(extendsStringList).isNotAssignableFrom(charSequenceCollection, charSequenceList, extendsCharSequenceList); } @Test @@ -1109,14 +1098,10 @@ public class ResolvableTypeTests { ResolvableType charSequenceArray = ResolvableType.forField(AssignmentBase.class.getField("carray"), Assignment.class); ResolvableType stringArray = ResolvableType.forField(AssignmentBase.class.getField("sarray"), Assignment.class); - assertAssignable(object, objectArray, charSequenceArray, stringArray). - equalTo(true, true, true); - assertAssignable(objectArray, object, objectArray, charSequenceArray, stringArray). - equalTo(false, true, true, true); - assertAssignable(charSequenceArray, object, objectArray, charSequenceArray, stringArray). - equalTo(false, false, true, true); - assertAssignable(stringArray, object, objectArray, charSequenceArray, stringArray). - equalTo(false, false, false, true); + assertThatResolvableType(object).isAssignableFrom(objectArray, charSequenceArray, stringArray); + assertThatResolvableType(objectArray).isAssignableFrom(objectArray, charSequenceArray, stringArray).isNotAssignableFrom(object); + assertThatResolvableType(charSequenceArray).isAssignableFrom(charSequenceArray, stringArray).isNotAssignableFrom(object, objectArray); + assertThatResolvableType(stringArray).isAssignableFrom(stringArray).isNotAssignableFrom(object, objectArray, charSequenceArray); } @Test @@ -1135,40 +1120,28 @@ public class ResolvableTypeTests { // Language Spec 4.5.1. Type Arguments and Wildcards // ? extends T <= ? extends S if T <: S - assertAssignable(extendsCharSequence, extendsObject, extendsCharSequence, extendsString). - equalTo(false, true, true); - assertAssignable(extendsCharSequence, object, charSequence, string). - equalTo(false, true, true); + assertThatResolvableType(extendsCharSequence).isAssignableFrom(extendsCharSequence, extendsString).isNotAssignableFrom(extendsObject); + assertThatResolvableType(extendsCharSequence).isAssignableFrom(charSequence, string).isNotAssignableFrom(object); // ? super T <= ? super S if S <: T - assertAssignable(superCharSequence, superObject, superCharSequence, superString). - equalTo(true, true, false); - assertAssignable(superCharSequence, object, charSequence, string). - equalTo(true, true, false); + assertThatResolvableType(superCharSequence).isAssignableFrom(superObject, superCharSequence).isNotAssignableFrom(superString); + assertThatResolvableType(superCharSequence).isAssignableFrom(object, charSequence).isNotAssignableFrom(string); // [Implied] super / extends cannot be mixed - assertAssignable(superCharSequence, extendsObject, extendsCharSequence, extendsString). - equalTo(false, false, false); - assertAssignable(extendsCharSequence, superObject, superCharSequence, superString). - equalTo(false, false, false); + assertThatResolvableType(superCharSequence).isNotAssignableFrom(extendsObject, extendsCharSequence, extendsString); + assertThatResolvableType(extendsCharSequence).isNotAssignableFrom(superObject, superCharSequence, superString); // T <= T - assertAssignable(charSequence, object, charSequence, string). - equalTo(false, true, true); + assertThatResolvableType(charSequence).isAssignableFrom(charSequence, string).isNotAssignableFrom(object); // T <= ? extends T - assertAssignable(extendsCharSequence, object, charSequence, string). - equalTo(false, true, true); - assertAssignable(charSequence, extendsObject, extendsCharSequence, extendsString). - equalTo(false, false, false); - assertAssignable(extendsAnon, object, charSequence, string). - equalTo(true, true, true); + assertThatResolvableType(extendsCharSequence).isAssignableFrom(charSequence, string).isNotAssignableFrom(object); + assertThatResolvableType(charSequence).isNotAssignableFrom(extendsObject, extendsCharSequence, extendsString); + assertThatResolvableType(extendsAnon).isAssignableFrom(object, charSequence, string); // T <= ? super T - assertAssignable(superCharSequence, object, charSequence, string). - equalTo(true, true, false); - assertAssignable(charSequence, superObject, superCharSequence, superString). - equalTo(false, false, false); + assertThatResolvableType(superCharSequence).isAssignableFrom(object, charSequence).isNotAssignableFrom(string); + assertThatResolvableType(charSequence).isNotAssignableFrom(superObject, superCharSequence, superString); } @Test @@ -1178,10 +1151,10 @@ public class ResolvableTypeTests { ResolvableType complex3 = ResolvableType.forField(AssignmentBase.class.getField("complexWildcard3")); ResolvableType complex4 = ResolvableType.forField(AssignmentBase.class.getField("complexWildcard4")); - assertAssignable(complex1, complex2).equalTo(true); - assertAssignable(complex2, complex1).equalTo(false); - assertAssignable(complex3, complex4).equalTo(true); - assertAssignable(complex4, complex3).equalTo(false); + assertThatResolvableType(complex1).isAssignableFrom(complex2); + assertThatResolvableType(complex2).isNotAssignableFrom(complex1); + assertThatResolvableType(complex3).isAssignableFrom(complex4); + assertThatResolvableType(complex4).isNotAssignableFrom(complex3); } @Test @@ -1191,43 +1164,43 @@ public class ResolvableTypeTests { ResolvableType forFieldViaType = ResolvableType.forType(Fields.class.getDeclaredField("stringList").getGenericType(), (VariableResolver) null); ResolvableType forFieldWithImplementation = ResolvableType.forField(Fields.class.getDeclaredField("stringList"), TypedFields.class); - assertThat(forClass, equalTo(forClass)); - assertThat(forClass.hashCode(), equalTo(forClass.hashCode())); - assertThat(forClass, not(equalTo(forFieldDirect))); - assertThat(forClass, not(equalTo(forFieldWithImplementation))); + assertThat(forClass).isEqualTo(forClass); + assertThat(forClass.hashCode()).isEqualTo(forClass.hashCode()); + assertThat(forClass).isNotEqualTo(forFieldDirect); + assertThat(forClass).isNotEqualTo(forFieldWithImplementation); - assertThat(forFieldDirect, equalTo(forFieldDirect)); - assertThat(forFieldDirect, not(equalTo(forFieldViaType))); - assertThat(forFieldDirect, not(equalTo(forFieldWithImplementation))); + assertThat(forFieldDirect).isEqualTo(forFieldDirect); + assertThat(forFieldDirect).isNotEqualTo(forFieldViaType); + assertThat(forFieldDirect).isNotEqualTo(forFieldWithImplementation); } @Test public void javaDocSample() throws Exception { ResolvableType t = ResolvableType.forField(getClass().getDeclaredField("myMap")); - assertThat(t.toString(), equalTo("java.util.HashMap>")); - assertThat(t.getType().getTypeName(), equalTo("java.util.HashMap>")); - assertThat(t.getType().toString(), equalTo("java.util.HashMap>")); - assertThat(t.getSuperType().toString(), equalTo("java.util.AbstractMap>")); - assertThat(t.asMap().toString(), equalTo("java.util.Map>")); - assertThat(t.getGeneric(0).resolve(), equalTo(Integer.class)); - assertThat(t.getGeneric(1).resolve(), equalTo(List.class)); - assertThat(t.getGeneric(1).toString(), equalTo("java.util.List")); - assertThat(t.resolveGeneric(1, 0), equalTo(String.class)); + assertThat(t.toString()).isEqualTo("java.util.HashMap>"); + assertThat(t.getType().getTypeName()).isEqualTo("java.util.HashMap>"); + assertThat(t.getType().toString()).isEqualTo("java.util.HashMap>"); + assertThat(t.getSuperType().toString()).isEqualTo("java.util.AbstractMap>"); + assertThat(t.asMap().toString()).isEqualTo("java.util.Map>"); + assertThat(t.getGeneric(0).resolve()).isEqualTo(Integer.class); + assertThat(t.getGeneric(1).resolve()).isEqualTo(List.class); + assertThat(t.getGeneric(1).toString()).isEqualTo("java.util.List"); + assertThat(t.resolveGeneric(1, 0)).isEqualTo(String.class); } @Test public void forClassWithGenerics() throws Exception { ResolvableType elementType = ResolvableType.forClassWithGenerics(Map.class, Integer.class, String.class); ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType); - assertThat(listType.toString(), equalTo("java.util.List>")); - assertThat(listType.getType().getTypeName(), equalTo("java.util.List>")); - assertThat(listType.getType().toString(), equalTo("java.util.List>")); + assertThat(listType.toString()).isEqualTo("java.util.List>"); + assertThat(listType.getType().getTypeName()).isEqualTo("java.util.List>"); + assertThat(listType.getType().toString()).isEqualTo("java.util.List>"); } @Test public void classWithGenericsAs() throws Exception { ResolvableType type = ResolvableType.forClassWithGenerics(MultiValueMap.class, Integer.class, String.class); - assertThat(type.asMap().toString(), equalTo("java.util.Map>")); + assertThat(type.asMap().toString()).isEqualTo("java.util.Map>"); } @Test @@ -1241,8 +1214,8 @@ public class ResolvableTypeTests { public void forArrayComponent() throws Exception { ResolvableType elementType = ResolvableType.forField(Fields.class.getField("stringList")); ResolvableType type = ResolvableType.forArrayComponent(elementType); - assertThat(type.toString(), equalTo("java.util.List[]")); - assertThat(type.resolve(), equalTo(List[].class)); + assertThat(type.toString()).isEqualTo("java.util.List[]"); + assertThat(type.resolve()).isEqualTo(List[].class); } @Test @@ -1254,56 +1227,56 @@ public class ResolvableTypeTests { testSerialization(ResolvableType.forConstructorParameter(Constructors.class.getConstructor(List.class), 0)); testSerialization(ResolvableType.forField(Fields.class.getField("charSequenceList")).getGeneric()); ResolvableType deserializedNone = testSerialization(ResolvableType.NONE); - assertThat(deserializedNone, sameInstance(ResolvableType.NONE)); + assertThat(deserializedNone).isSameAs(ResolvableType.NONE); } @Test public void canResolveVoid() throws Exception { ResolvableType type = ResolvableType.forClass(void.class); - assertThat(type.resolve(), equalTo(void.class)); + assertThat(type.resolve()).isEqualTo(void.class); } @Test public void narrow() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringList")); ResolvableType narrow = ResolvableType.forType(ArrayList.class, type); - assertThat(narrow.getGeneric().resolve(), equalTo(String.class)); + assertThat(narrow.getGeneric().resolve()).isEqualTo(String.class); } @Test public void hasUnresolvableGenerics() throws Exception { ResolvableType type = ResolvableType.forField(Fields.class.getField("stringList")); - assertThat(type.hasUnresolvableGenerics(), equalTo(false)); + assertThat(type.hasUnresolvableGenerics()).isEqualTo(false); } @Test public void hasUnresolvableGenericsBasedOnOwnGenerics() throws Exception { ResolvableType type = ResolvableType.forClass(List.class); - assertThat(type.hasUnresolvableGenerics(), equalTo(true)); + assertThat(type.hasUnresolvableGenerics()).isEqualTo(true); } @Test public void hasUnresolvableGenericsWhenSelfNotResolvable() throws Exception { ResolvableType type = ResolvableType.forClass(List.class).getGeneric(); - assertThat(type.hasUnresolvableGenerics(), equalTo(false)); + assertThat(type.hasUnresolvableGenerics()).isEqualTo(false); } @Test public void hasUnresolvableGenericsWhenImplementesRawInterface() throws Exception { ResolvableType type = ResolvableType.forClass(MySimpleInterfaceTypeWithImplementsRaw.class); for (ResolvableType generic : type.getGenerics()) { - assertThat(generic.resolve(), not(nullValue())); + assertThat(generic.resolve()).isNotNull(); } - assertThat(type.hasUnresolvableGenerics(), equalTo(true)); + assertThat(type.hasUnresolvableGenerics()).isEqualTo(true); } @Test public void hasUnresolvableGenericsWhenExtends() throws Exception { ResolvableType type = ResolvableType.forClass(ExtendsMySimpleInterfaceTypeWithImplementsRaw.class); for (ResolvableType generic : type.getGenerics()) { - assertThat(generic.resolve(), not(nullValue())); + assertThat(generic.resolve()).isNotNull(); } - assertThat(type.hasUnresolvableGenerics(), equalTo(true)); + assertThat(type.hasUnresolvableGenerics()).isEqualTo(true); } @Test @@ -1317,10 +1290,10 @@ public class ResolvableTypeTests { public void testSpr12701() throws Exception { ResolvableType resolvableType = ResolvableType.forClassWithGenerics(Callable.class, String.class); Type type = resolvableType.getType(); - assertThat(type, is(instanceOf(ParameterizedType.class))); - assertThat(((ParameterizedType) type).getRawType(), is(equalTo(Callable.class))); - assertThat(((ParameterizedType) type).getActualTypeArguments().length, is(equalTo(1))); - assertThat(((ParameterizedType) type).getActualTypeArguments()[0], is(equalTo(String.class))); + assertThat(type).isInstanceOf(ParameterizedType.class); + assertThat(((ParameterizedType) type).getRawType()).isEqualTo(Callable.class); + assertThat(((ParameterizedType) type).getActualTypeArguments().length).isEqualTo(1); + assertThat(((ParameterizedType) type).getActualTypeArguments()[0]).isEqualTo(String.class); } @Test @@ -1337,7 +1310,7 @@ public class ResolvableTypeTests { ResolvableType genericType = ResolvableType.forField( UnresolvedWithGenerics.class.getDeclaredField("set")).asCollection(); ResolvableType type = ResolvableType.forClassWithGenerics(ArrayList.class, genericType.getGeneric()); - assertThat(type.resolveGeneric(), equalTo(Integer.class)); + assertThat(type.resolveGeneric()).isEqualTo(Integer.class); } @@ -1348,52 +1321,28 @@ public class ResolvableTypeTests { oos.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); ResolvableType read = (ResolvableType) ois.readObject(); - assertThat(read, equalTo(type)); - assertThat(read.getType(), equalTo(type.getType())); - assertThat(read.resolve(), equalTo(type.resolve())); + assertThat(read).isEqualTo(type); + assertThat(read.getType()).isEqualTo(type.getType()); + assertThat(read.resolve()).isEqualTo(type.resolve()); return read; } - private void assertFieldToStringValue(String field, String expected) throws Exception { - ResolvableType type = ResolvableType.forField(Fields.class.getField(field)); - assertThat("field " + field + " toString", type.toString(), equalTo(expected)); + private ResolvableType forField(String field) throws NoSuchFieldException { + return ResolvableType.forField(Fields.class.getField(field)); } - private void assertTypedFieldToStringValue(String field, String expected) throws Exception { - ResolvableType type = ResolvableType.forField(Fields.class.getField(field), TypedFields.class); - assertThat("field " + field + " toString", type.toString(), equalTo(expected)); + private ResolvableType forTypedField(String field) throws NoSuchFieldException { + return ResolvableType.forField(Fields.class.getField(field), TypedFields.class); } - private AssertAssignbleMatcher assertAssignable(final ResolvableType type, final ResolvableType... fromTypes) { - return values -> { - for (int i = 0; i < fromTypes.length; i++) { - assertThat(stringDesc(type) + " isAssignableFrom " + stringDesc(fromTypes[i]), - type.isAssignableFrom(fromTypes[i]), equalTo(values[i])); - } - }; + private static ResolvableTypeAssert assertThatResolvableType(ResolvableType type) { + return new ResolvableTypeAssert(type); } - private String stringDesc(ResolvableType type) { - if (type == ResolvableType.NONE) { - return "NONE"; - } - if (type.getType().getClass().equals(Class.class)) { - return type.toString(); - } - return type.getType() + ":" + type; - } - - @SuppressWarnings("unused") private HashMap> myMap; - private interface AssertAssignbleMatcher { - - void equalTo(boolean... values); - } - - @SuppressWarnings("serial") static class ExtendsList extends ArrayList { } @@ -1657,4 +1606,40 @@ public class ResolvableTypeTests { Set set; } + private static class ResolvableTypeAssert extends AbstractAssert{ + + public ResolvableTypeAssert(ResolvableType actual) { + super(actual, ResolvableTypeAssert.class); + } + + public ResolvableTypeAssert isAssignableFrom(ResolvableType... types) { + for (ResolvableType type : types) { + if (!actual.isAssignableFrom(type)) { + throw new AssertionError("Expecting " + decribe(actual) + " to be assignable from " + decribe(type)); + } + } + return this; + } + + public ResolvableTypeAssert isNotAssignableFrom(ResolvableType... types) { + for (ResolvableType type : types) { + if (actual.isAssignableFrom(type)) { + throw new AssertionError("Expecting " + decribe(actual) + " to not be assignable from " + decribe(type)); + } + } + return this; + } + + private String decribe(ResolvableType type) { + if (type == ResolvableType.NONE) { + return "NONE"; + } + if (type.getType().getClass().equals(Class.class)) { + return type.toString(); + } + return type.getType() + ":" + type; + } + + } + } diff --git a/spring-core/src/test/java/org/springframework/core/SerializableTypeWrapperTests.java b/spring-core/src/test/java/org/springframework/core/SerializableTypeWrapperTests.java index 831324c35d..e0610c0749 100644 --- a/spring-core/src/test/java/org/springframework/core/SerializableTypeWrapperTests.java +++ b/spring-core/src/test/java/org/springframework/core/SerializableTypeWrapperTests.java @@ -31,8 +31,9 @@ import java.util.List; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; + + /** * Tests for {@link SerializableTypeWrapper}. @@ -44,7 +45,7 @@ public class SerializableTypeWrapperTests { @Test public void forField() throws Exception { Type type = SerializableTypeWrapper.forField(Fields.class.getField("parameterizedType")); - assertThat(type.toString(), equalTo("java.util.List")); + assertThat(type.toString()).isEqualTo("java.util.List"); assertSerializable(type); } @@ -52,7 +53,7 @@ public class SerializableTypeWrapperTests { public void forMethodParameter() throws Exception { Method method = Methods.class.getDeclaredMethod("method", Class.class, Object.class); Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forExecutable(method, 0)); - assertThat(type.toString(), equalTo("java.lang.Class")); + assertThat(type.toString()).isEqualTo("java.lang.Class"); assertSerializable(type); } @@ -60,21 +61,21 @@ public class SerializableTypeWrapperTests { public void forConstructor() throws Exception { Constructor constructor = Constructors.class.getDeclaredConstructor(List.class); Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forExecutable(constructor, 0)); - assertThat(type.toString(), equalTo("java.util.List")); + assertThat(type.toString()).isEqualTo("java.util.List"); assertSerializable(type); } @Test public void classType() throws Exception { Type type = SerializableTypeWrapper.forField(Fields.class.getField("classType")); - assertThat(type.toString(), equalTo("class java.lang.String")); + assertThat(type.toString()).isEqualTo("class java.lang.String"); assertSerializable(type); } @Test public void genericArrayType() throws Exception { GenericArrayType type = (GenericArrayType) SerializableTypeWrapper.forField(Fields.class.getField("genericArrayType")); - assertThat(type.toString(), equalTo("java.util.List[]")); + assertThat(type.toString()).isEqualTo("java.util.List[]"); assertSerializable(type); assertSerializable(type.getGenericComponentType()); } @@ -82,7 +83,7 @@ public class SerializableTypeWrapperTests { @Test public void parameterizedType() throws Exception { ParameterizedType type = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("parameterizedType")); - assertThat(type.toString(), equalTo("java.util.List")); + assertThat(type.toString()).isEqualTo("java.util.List"); assertSerializable(type); assertSerializable(type.getOwnerType()); assertSerializable(type.getRawType()); @@ -93,7 +94,7 @@ public class SerializableTypeWrapperTests { @Test public void typeVariableType() throws Exception { TypeVariable type = (TypeVariable) SerializableTypeWrapper.forField(Fields.class.getField("typeVariableType")); - assertThat(type.toString(), equalTo("T")); + assertThat(type.toString()).isEqualTo("T"); assertSerializable(type); assertSerializable(type.getBounds()); } @@ -102,7 +103,7 @@ public class SerializableTypeWrapperTests { public void wildcardType() throws Exception { ParameterizedType typeSource = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("wildcardType")); WildcardType type = (WildcardType) typeSource.getActualTypeArguments()[0]; - assertThat(type.toString(), equalTo("? extends java.lang.CharSequence")); + assertThat(type.toString()).isEqualTo("? extends java.lang.CharSequence"); assertSerializable(type); assertSerializable(type.getLowerBounds()); assertSerializable(type.getUpperBounds()); @@ -115,7 +116,7 @@ public class SerializableTypeWrapperTests { oos.writeObject(source); oos.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); - assertThat(ois.readObject(), equalTo(source)); + assertThat(ois.readObject()).isEqualTo(source); } diff --git a/spring-core/src/test/java/org/springframework/core/StandardReflectionParameterNameDiscoverTests.java b/spring-core/src/test/java/org/springframework/core/StandardReflectionParameterNameDiscoverTests.java index e9c27eaaf3..2f20f4cd79 100644 --- a/spring-core/src/test/java/org/springframework/core/StandardReflectionParameterNameDiscoverTests.java +++ b/spring-core/src/test/java/org/springframework/core/StandardReflectionParameterNameDiscoverTests.java @@ -22,8 +22,8 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests for StandardReflectionParameterNameDiscoverer @@ -42,7 +42,7 @@ public class StandardReflectionParameterNameDiscoverTests { public void getParameterNamesOnInterface() { Method method = ReflectionUtils.findMethod(MessageService.class,"sendMessage", String.class); String[] actualParams = parameterNameDiscoverer.getParameterNames(method); - assertThat(actualParams, is(new String[]{"message"})); + assertThat(actualParams).isEqualTo(new String[]{"message"}); } public interface MessageService { diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java index 0c6bb366f9..58e250fcfa 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java @@ -25,10 +25,8 @@ import org.junit.Test; import org.springframework.core.annotation.AnnotationUtilsTests.ImplicitAliasesContextConfig; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -64,16 +62,16 @@ public class AnnotationAttributesTests { attributes.put("anno", nestedAttributes); attributes.put("annoArray", new AnnotationAttributes[] {nestedAttributes}); - assertThat(attributes.getString("name"), equalTo("dave")); - assertThat(attributes.getStringArray("names"), equalTo(new String[] {"dave", "frank", "hal"})); - assertThat(attributes.getBoolean("bool1"), equalTo(true)); - assertThat(attributes.getBoolean("bool2"), equalTo(false)); - assertThat(attributes.getEnum("color"), equalTo(Color.RED)); + assertThat(attributes.getString("name")).isEqualTo("dave"); + assertThat(attributes.getStringArray("names")).isEqualTo(new String[] {"dave", "frank", "hal"}); + assertThat(attributes.getBoolean("bool1")).isEqualTo(true); + assertThat(attributes.getBoolean("bool2")).isEqualTo(false); + assertThat(attributes.getEnum("color")).isEqualTo(Color.RED); assertTrue(attributes.getClass("class").equals(Integer.class)); - assertThat(attributes.getClassArray("classes"), equalTo(new Class[] {Number.class, Short.class, Integer.class})); - assertThat(attributes.getNumber("number"), equalTo(42)); - assertThat(attributes.getAnnotation("anno").getNumber("value"), equalTo(10)); - assertThat(attributes.getAnnotationArray("annoArray")[0].getString("name"), equalTo("algernon")); + assertThat(attributes.getClassArray("classes")).isEqualTo(new Class[] {Number.class, Short.class, Integer.class}); + assertThat(attributes.getNumber("number")).isEqualTo(42); + assertThat(attributes.getAnnotation("anno").getNumber("value")).isEqualTo(10); + assertThat(attributes.getAnnotationArray("annoArray")[0].getString("name")).isEqualTo("algernon"); } @@ -99,18 +97,18 @@ public class AnnotationAttributesTests { attributes.put("filters", filter); // Get back arrays of single elements - assertThat(attributes.getStringArray("names"), equalTo(new String[] {"Dogbert"})); - assertThat(attributes.getClassArray("classes"), equalTo(new Class[] {Number.class})); + assertThat(attributes.getStringArray("names")).isEqualTo(new String[] {"Dogbert"}); + assertThat(attributes.getClassArray("classes")).isEqualTo(new Class[] {Number.class}); AnnotationAttributes[] array = attributes.getAnnotationArray("nestedAttributes"); assertNotNull(array); - assertThat(array.length, is(1)); - assertThat(array[0].getString("name"), equalTo("Dilbert")); + assertThat(array.length).isEqualTo(1); + assertThat(array[0].getString("name")).isEqualTo("Dilbert"); Filter[] filters = attributes.getAnnotationArray("filters", Filter.class); assertNotNull(filters); - assertThat(filters.length, is(1)); - assertThat(filters[0].pattern(), equalTo("foo")); + assertThat(filters.length).isEqualTo(1); + assertThat(filters[0].pattern()).isEqualTo("foo"); } @Test @@ -121,13 +119,13 @@ public class AnnotationAttributesTests { attributes.put("filters", new Filter[] {filter, filter}); Filter retrievedFilter = attributes.getAnnotation("filter", Filter.class); - assertThat(retrievedFilter, equalTo(filter)); - assertThat(retrievedFilter.pattern(), equalTo("foo")); + assertThat(retrievedFilter).isEqualTo(filter); + assertThat(retrievedFilter.pattern()).isEqualTo("foo"); Filter[] retrievedFilters = attributes.getAnnotationArray("filters", Filter.class); assertNotNull(retrievedFilters); assertEquals(2, retrievedFilters.length); - assertThat(retrievedFilters[1].pattern(), equalTo("foo")); + assertThat(retrievedFilters[1].pattern()).isEqualTo("foo"); } @Test 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 ae1bb19f28..5d57dee95d 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 @@ -22,9 +22,7 @@ import javax.annotation.Priority; import org.junit.Test; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -37,7 +35,7 @@ public class AnnotationAwareOrderComparatorTests { @Test public void instanceVariableIsAnAnnotationAwareOrderComparator() { - assertThat(AnnotationAwareOrderComparator.INSTANCE, is(instanceOf(AnnotationAwareOrderComparator.class))); + assertThat(AnnotationAwareOrderComparator.INSTANCE).isInstanceOf(AnnotationAwareOrderComparator.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 22de2208b5..27c9142d06 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 @@ -43,10 +43,9 @@ import org.springframework.stereotype.Component; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -581,7 +580,7 @@ public class AnnotationUtilsTests { Set annotations = getRepeatableAnnotations(method, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(annotations); List values = annotations.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(asList("A", "B", "C", "meta1"))); + assertThat(values).isEqualTo(asList("A", "B", "C", "meta1")); } @Test @@ -606,10 +605,10 @@ public class AnnotationUtilsTests { assertNotNull(annotations); List locations = annotations.stream().map(ContextConfig::location).collect(toList()); - assertThat(locations, is(expectedLocations)); + assertThat(locations).isEqualTo(expectedLocations); List values = annotations.stream().map(ContextConfig::value).collect(toList()); - assertThat(values, is(expectedLocations)); + assertThat(values).isEqualTo(expectedLocations); } @Test @@ -621,19 +620,19 @@ public class AnnotationUtilsTests { MyRepeatable[] array = MyRepeatableClass.class.getAnnotationsByType(MyRepeatable.class); assertNotNull(array); List values = stream(array).map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesJava)); + assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); } @Test @@ -646,19 +645,19 @@ public class AnnotationUtilsTests { MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class); assertNotNull(array); List values = stream(array).map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesJava)); + assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(clazz, MyRepeatable.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); } @Test @@ -671,19 +670,19 @@ public class AnnotationUtilsTests { MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class); assertNotNull(array); List values = stream(array).map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesJava)); + assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(clazz, MyRepeatable.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); } @Test @@ -696,19 +695,19 @@ public class AnnotationUtilsTests { MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class); assertNotNull(array); List values = stream(array).map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesJava)); + assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(clazz, MyRepeatable.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); } @Test @@ -720,19 +719,19 @@ public class AnnotationUtilsTests { MyRepeatable[] array = MyRepeatableClass.class.getDeclaredAnnotationsByType(MyRepeatable.class); assertNotNull(array); List values = stream(array).map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesJava)); + assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class); assertNotNull(set); values = set.stream().map(MyRepeatable::value).collect(toList()); - assertThat(values, is(expectedValuesSpring)); + assertThat(values).isEqualTo(expectedValuesSpring); } @Test @@ -742,17 +741,17 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = clazz.getDeclaredAnnotationsByType(MyRepeatable.class); assertNotNull(array); - assertThat(array.length, is(0)); + assertThat(array.length).isEqualTo(0); // Spring Set set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); assertNotNull(set); - assertThat(set.size(), is(0)); + assertThat(set).hasSize(0); // When container type is omitted and therefore inferred from @Repeatable set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class); assertNotNull(set); - assertThat(set.size(), is(0)); + assertThat(set).hasSize(0); } @Test 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 31cdab81fc..9d48a8a385 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 @@ -42,10 +42,8 @@ import org.springframework.core.MethodParameter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -742,29 +740,29 @@ public class TypeDescriptorTests { ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream( out.toByteArray())); TypeDescriptor readObject = (TypeDescriptor) inputStream.readObject(); - assertThat(readObject, equalTo(typeDescriptor)); + assertThat(readObject).isEqualTo(typeDescriptor); } @Test public void createCollectionWithNullElement() throws Exception { TypeDescriptor typeDescriptor = TypeDescriptor.collection(List.class, null); - assertThat(typeDescriptor.getElementTypeDescriptor(), nullValue()); + assertThat(typeDescriptor.getElementTypeDescriptor()).isNull(); } @Test public void createMapWithNullElements() throws Exception { TypeDescriptor typeDescriptor = TypeDescriptor.map(LinkedHashMap.class, null, null); - assertThat(typeDescriptor.getMapKeyTypeDescriptor(), nullValue()); - assertThat(typeDescriptor.getMapValueTypeDescriptor(), nullValue()); + assertThat(typeDescriptor.getMapKeyTypeDescriptor()).isNull(); + assertThat(typeDescriptor.getMapValueTypeDescriptor()).isNull(); } @Test public void getSource() throws Exception { Field field = getClass().getField("fieldScalar"); MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterPrimitive", int.class), 0); - assertThat(new TypeDescriptor(field).getSource(), equalTo((Object) field)); - assertThat(new TypeDescriptor(methodParameter).getSource(), equalTo((Object) methodParameter)); - assertThat(TypeDescriptor.valueOf(Integer.class).getSource(), equalTo((Object) Integer.class)); + assertThat(new TypeDescriptor(field).getSource()).isEqualTo(field); + assertThat(new TypeDescriptor(methodParameter).getSource()).isEqualTo(methodParameter); + assertThat(TypeDescriptor.valueOf(Integer.class).getSource()).isEqualTo(Integer.class); } diff --git a/spring-core/src/test/java/org/springframework/core/convert/converter/ConvertingComparatorTests.java b/spring-core/src/test/java/org/springframework/core/convert/converter/ConvertingComparatorTests.java index ba793ed5ec..711b2f7bfb 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/converter/ConvertingComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/converter/ConvertingComparatorTests.java @@ -29,10 +29,9 @@ import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.util.comparator.ComparableComparator; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; + /** * Tests for {@link ConvertingComparator}. @@ -91,9 +90,9 @@ public class ConvertingComparatorTests { } private void testConversion(ConvertingComparator convertingComparator) { - assertThat(convertingComparator.compare("0", "0"), is(0)); - assertThat(convertingComparator.compare("0", "1"), is(-1)); - assertThat(convertingComparator.compare("1", "0"), is(1)); + assertThat(convertingComparator.compare("0", "0")).isEqualTo(0); + assertThat(convertingComparator.compare("0", "1")).isEqualTo(-1); + assertThat(convertingComparator.compare("1", "0")).isEqualTo(1); comparator.assertCalled(); } @@ -102,7 +101,7 @@ public class ConvertingComparatorTests { ArrayList> list = createReverseOrderMapEntryList(); Comparator> comparator = ConvertingComparator.mapEntryKeys(new ComparableComparator()); Collections.sort(list, comparator); - assertThat(list.get(0).getKey(), is("a")); + assertThat(list.get(0).getKey()).isEqualTo("a"); } @Test @@ -110,7 +109,7 @@ public class ConvertingComparatorTests { ArrayList> list = createReverseOrderMapEntryList(); Comparator> comparator = ConvertingComparator.mapEntryValues(new ComparableComparator()); Collections.sort(list, comparator); - assertThat(list.get(0).getValue(), is(1)); + assertThat(list.get(0).getValue()).isEqualTo(1); } private ArrayList> createReverseOrderMapEntryList() { @@ -119,7 +118,7 @@ public class ConvertingComparatorTests { map.put("a", 1); ArrayList> list = new ArrayList<>( map.entrySet()); - assertThat(list.get(0).getKey(), is("b")); + assertThat(list.get(0).getKey()).isEqualTo("b"); return list; } @@ -139,14 +138,14 @@ public class ConvertingComparatorTests { @Override public int compare(Integer o1, Integer o2) { - assertThat(o1, instanceOf(Integer.class)); - assertThat(o2, instanceOf(Integer.class)); + assertThat(o1).isInstanceOf(Integer.class); + assertThat(o2).isInstanceOf(Integer.class); this.called = true; return super.compare(o1, o2); }; public void assertCalled() { - assertThat(this.called, is(true)); + assertThat(this.called).isTrue(); } } 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 f06d47b81c..0e24c037e1 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 @@ -56,9 +56,8 @@ import org.springframework.tests.TestGroup; import org.springframework.util.ClassUtils; import org.springframework.util.StopWatch; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -657,7 +656,7 @@ public class DefaultConversionServiceTests { public void convertByteArrayToWrapperArray() { byte[] byteArray = new byte[] {1, 2, 3}; Byte[] converted = conversionService.convert(byteArray, Byte[].class); - assertThat(converted, equalTo(new Byte[]{1, 2, 3})); + assertThat(converted).isEqualTo(new Byte[]{1, 2, 3}); } @Test @@ -914,20 +913,20 @@ public class DefaultConversionServiceTests { @Test public void convertCharArrayToString() { String converted = conversionService.convert(new char[] {'a', 'b', 'c'}, String.class); - assertThat(converted, equalTo("a,b,c")); + assertThat(converted).isEqualTo("a,b,c"); } @Test public void convertStringToCharArray() { char[] converted = conversionService.convert("a,b,c", char[].class); - assertThat(converted, equalTo(new char[]{'a', 'b', 'c'})); + assertThat(converted).isEqualTo(new char[]{'a', 'b', 'c'}); } @Test public void convertStringToCustomCharArray() { conversionService.addConverter(String.class, char[].class, String::toCharArray); char[] converted = conversionService.convert("abc", char[].class); - assertThat(converted, equalTo(new char[] {'a', 'b', 'c'})); + assertThat(converted).isEqualTo(new char[] {'a', 'b', 'c'}); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/ByteBufferConverterTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/ByteBufferConverterTests.java index 9dbf465996..4f29bfd38e 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/ByteBufferConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/ByteBufferConverterTests.java @@ -23,10 +23,11 @@ import org.junit.Test; import org.springframework.core.convert.converter.Converter; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; + + + + /** * Tests for {@link ByteBufferConverter}. @@ -51,8 +52,8 @@ public class ByteBufferConverterTests { public void byteArrayToByteBuffer() throws Exception { byte[] bytes = new byte[] { 1, 2, 3 }; ByteBuffer convert = this.conversionService.convert(bytes, ByteBuffer.class); - assertThat(convert.array(), not(sameInstance(bytes))); - assertThat(convert.array(), equalTo(bytes)); + assertThat(convert.array()).isNotSameAs(bytes); + assertThat(convert.array()).isEqualTo(bytes); } @Test @@ -60,8 +61,8 @@ public class ByteBufferConverterTests { byte[] bytes = new byte[] { 1, 2, 3 }; ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); byte[] convert = this.conversionService.convert(byteBuffer, byte[].class); - assertThat(convert, not(sameInstance(bytes))); - assertThat(convert, equalTo(bytes)); + assertThat(convert).isNotSameAs(bytes); + assertThat(convert).isEqualTo(bytes); } @Test @@ -69,8 +70,8 @@ public class ByteBufferConverterTests { byte[] bytes = new byte[] { 1, 2, 3 }; ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); OtherType convert = this.conversionService.convert(byteBuffer, OtherType.class); - assertThat(convert.bytes, not(sameInstance(bytes))); - assertThat(convert.bytes, equalTo(bytes)); + assertThat(convert.bytes).isNotSameAs(bytes); + assertThat(convert.bytes).isEqualTo(bytes); } @Test @@ -78,8 +79,8 @@ public class ByteBufferConverterTests { byte[] bytes = new byte[] { 1, 2, 3 }; OtherType otherType = new OtherType(bytes); ByteBuffer convert = this.conversionService.convert(otherType, ByteBuffer.class); - assertThat(convert.array(), not(sameInstance(bytes))); - assertThat(convert.array(), equalTo(bytes)); + assertThat(convert.array()).isNotSameAs(bytes); + assertThat(convert.array()).isEqualTo(bytes); } @Test @@ -87,10 +88,10 @@ public class ByteBufferConverterTests { byte[] bytes = new byte[] { 1, 2, 3 }; ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); ByteBuffer convert = this.conversionService.convert(byteBuffer, ByteBuffer.class); - assertThat(convert, not(sameInstance(byteBuffer.rewind()))); - assertThat(convert, equalTo(byteBuffer.rewind())); - assertThat(convert, equalTo(ByteBuffer.wrap(bytes))); - assertThat(convert.array(), equalTo(bytes)); + assertThat(convert).isNotSameAs(byteBuffer.rewind()); + assertThat(convert).isEqualTo(byteBuffer.rewind()); + assertThat(convert).isEqualTo(ByteBuffer.wrap(bytes)); + assertThat(convert.array()).isEqualTo(bytes); } 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 7cd8c7c129..13fca1c0bf 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 @@ -51,11 +51,10 @@ import org.springframework.util.StringUtils; import static java.util.Comparator.naturalOrder; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -527,7 +526,7 @@ public class GenericConversionServiceTests { MyConditionalGenericConverter converter = new MyConditionalGenericConverter(); conversionService.addConverter(converter); assertEquals((Integer) 3, conversionService.convert(3, Integer.class)); - assertThat(converter.getSourceTypes().size(), greaterThan(2)); + assertThat(converter.getSourceTypes().size()).isGreaterThan(2); assertTrue(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType()))); } 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 d1dc5e1a3c..f7af7d354d 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 @@ -33,9 +33,8 @@ import org.springframework.core.convert.TypeDescriptor; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -245,9 +244,9 @@ public class MapToMapConverterTests { TypeDescriptor targetType = new TypeDescriptor(getClass().getField("multiValueMapTarget")); MultiValueMap converted = (MultiValueMap) conversionService.convert(source, targetType); - assertThat(converted.size(), equalTo(2)); - assertThat(converted.get("a"), equalTo(Arrays.asList("1", "2", "3"))); - assertThat(converted.get("b"), equalTo(Arrays.asList("4", "5", "6"))); + assertThat(converted.size()).isEqualTo(2); + assertThat(converted.get("a")).isEqualTo(Arrays.asList("1", "2", "3")); + assertThat(converted.get("b")).isEqualTo(Arrays.asList("4", "5", "6")); } @Test @@ -260,9 +259,9 @@ public class MapToMapConverterTests { TypeDescriptor targetType = new TypeDescriptor(getClass().getField("multiValueMapTarget")); MultiValueMap converted = (MultiValueMap) conversionService.convert(source, targetType); - assertThat(converted.size(), equalTo(2)); - assertThat(converted.get("a"), equalTo(Arrays.asList("1"))); - assertThat(converted.get("b"), equalTo(Arrays.asList("2"))); + assertThat(converted.size()).isEqualTo(2); + assertThat(converted.get("a")).isEqualTo(Arrays.asList("1")); + assertThat(converted.get("b")).isEqualTo(Arrays.asList("2")); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/env/CustomEnvironmentTests.java b/spring-core/src/test/java/org/springframework/core/env/CustomEnvironmentTests.java index 440eae3716..5fc88c6dde 100644 --- a/spring-core/src/test/java/org/springframework/core/env/CustomEnvironmentTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/CustomEnvironmentTests.java @@ -22,8 +22,8 @@ import java.util.Set; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests covering the extensibility of {@link AbstractEnvironment}. @@ -38,7 +38,7 @@ public class CustomEnvironmentTests { @Test public void control() { Environment env = new AbstractEnvironment() { }; - assertThat(env.acceptsProfiles(defaultProfile()), is(true)); + assertThat(env.acceptsProfiles(defaultProfile())).isTrue(); } @Test @@ -51,7 +51,7 @@ public class CustomEnvironmentTests { } Environment env = new CustomEnvironment(); - assertThat(env.acceptsProfiles(defaultProfile()), is(false)); + assertThat(env.acceptsProfiles(defaultProfile())).isFalse(); } @Test @@ -64,8 +64,8 @@ public class CustomEnvironmentTests { } Environment env = new CustomEnvironment(); - assertThat(env.acceptsProfiles(defaultProfile()), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("rd1")), is(true)); + assertThat(env.acceptsProfiles(defaultProfile())).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("rd1"))).isTrue(); } @Test @@ -82,28 +82,28 @@ public class CustomEnvironmentTests { } ConfigurableEnvironment env = new CustomEnvironment(); - assertThat(env.acceptsProfiles(defaultProfile()), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2")), is(true)); + assertThat(env.acceptsProfiles(defaultProfile())).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2"))).isTrue(); // finally, issue additional assertions to cover all combinations of calling these // methods, however unlikely. env.setDefaultProfiles("d1"); - assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2")), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("d1")), is(true)); + assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2"))).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("d1"))).isTrue(); env.setActiveProfiles("a1", "a2"); - assertThat(env.acceptsProfiles(Profiles.of("d1")), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("a1 | a2")), is(true)); + assertThat(env.acceptsProfiles(Profiles.of("d1"))).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("a1 | a2"))).isTrue(); env.setActiveProfiles(); - assertThat(env.acceptsProfiles(Profiles.of("d1")), is(true)); - assertThat(env.acceptsProfiles(Profiles.of("a1 | a2")), is(false)); + assertThat(env.acceptsProfiles(Profiles.of("d1"))).isTrue(); + assertThat(env.acceptsProfiles(Profiles.of("a1 | a2"))).isFalse(); env.setDefaultProfiles(); - assertThat(env.acceptsProfiles(defaultProfile()), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2")), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("d1")), is(false)); - assertThat(env.acceptsProfiles(Profiles.of("a1 | a2")), is(false)); + assertThat(env.acceptsProfiles(defaultProfile())).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2"))).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("d1"))).isFalse(); + assertThat(env.acceptsProfiles(Profiles.of("a1 | a2"))).isFalse(); } private Profiles defaultProfile() { diff --git a/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java index 7ecb8c8cd2..cea64244cf 100644 --- a/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java @@ -22,10 +22,7 @@ import joptsimple.OptionParser; import joptsimple.OptionSet; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -43,7 +40,7 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--foo=bar"); PropertySource ps = new JOptCommandLinePropertySource(options); - assertThat((String)ps.getProperty("foo"), equalTo("bar")); + assertThat((String)ps.getProperty("foo")).isEqualTo("bar"); } @Test @@ -53,8 +50,8 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--foo"); PropertySource ps = new JOptCommandLinePropertySource(options); - assertThat(ps.containsProperty("foo"), is(true)); - assertThat((String)ps.getProperty("foo"), equalTo("")); + assertThat(ps.containsProperty("foo")).isTrue(); + assertThat((String)ps.getProperty("foo")).isEqualTo(""); } @Test @@ -65,10 +62,10 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--o1"); PropertySource ps = new JOptCommandLinePropertySource(options); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(false)); - assertThat((String)ps.getProperty("o1"), equalTo("")); - assertThat(ps.getProperty("o2"), nullValue()); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isFalse(); + assertThat((String)ps.getProperty("o1")).isEqualTo(""); + assertThat(ps.getProperty("o2")).isNull(); } @Test @@ -79,7 +76,7 @@ public class JOptCommandLinePropertySourceTests { CommandLinePropertySource ps = new JOptCommandLinePropertySource(options); assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo")); - assertThat(ps.getProperty("foo"), equalTo("bar,baz,biz")); + assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz"); } @Test @@ -90,7 +87,7 @@ public class JOptCommandLinePropertySourceTests { CommandLinePropertySource ps = new JOptCommandLinePropertySource(options); assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo")); - assertThat(ps.getProperty("foo"), equalTo("bar,baz,biz")); + assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz"); } @Test @@ -100,7 +97,7 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse(); // <-- no options whatsoever PropertySource ps = new JOptCommandLinePropertySource(options); - assertThat(ps.getProperty("foo"), nullValue()); + assertThat(ps.getProperty("foo")).isNull(); } @Test @@ -110,7 +107,7 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--spring.profiles.active=p1"); CommandLinePropertySource ps = new JOptCommandLinePropertySource(options); - assertThat(ps.getProperty("spring.profiles.active"), equalTo("p1")); + assertThat(ps.getProperty("spring.profiles.active")).isEqualTo("p1"); } @Test @@ -121,13 +118,13 @@ public class JOptCommandLinePropertySourceTests { OptionSet optionSet = parser.parse("--o1=v1", "--o2"); EnumerablePropertySource ps = new JOptCommandLinePropertySource(optionSet); - assertThat(ps.containsProperty("nonOptionArgs"), is(false)); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("nonOptionArgs")).isFalse(); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); - assertThat(ps.containsProperty("nonOptionArgs"), is(false)); - assertThat(ps.getProperty("nonOptionArgs"), nullValue()); - assertThat(ps.getPropertyNames().length, is(2)); + assertThat(ps.containsProperty("nonOptionArgs")).isFalse(); + assertThat(ps.getProperty("nonOptionArgs")).isNull(); + assertThat(ps.getPropertyNames().length).isEqualTo(2); } @Test @@ -138,12 +135,12 @@ public class JOptCommandLinePropertySourceTests { OptionSet optionSet = parser.parse("--o1=v1", "noa1", "--o2", "noa2"); PropertySource ps = new JOptCommandLinePropertySource(optionSet); - assertThat(ps.containsProperty("nonOptionArgs"), is(true)); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("nonOptionArgs")).isTrue(); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); String nonOptionArgs = (String)ps.getProperty("nonOptionArgs"); - assertThat(nonOptionArgs, equalTo("noa1,noa2")); + assertThat(nonOptionArgs).isEqualTo("noa1,noa2"); } @Test @@ -155,12 +152,12 @@ public class JOptCommandLinePropertySourceTests { CommandLinePropertySource ps = new JOptCommandLinePropertySource(optionSet); ps.setNonOptionArgsPropertyName("NOA"); - assertThat(ps.containsProperty("nonOptionArgs"), is(false)); - assertThat(ps.containsProperty("NOA"), is(true)); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("nonOptionArgs")).isFalse(); + assertThat(ps.containsProperty("NOA")).isTrue(); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); String nonOptionArgs = ps.getProperty("NOA"); - assertThat(nonOptionArgs, equalTo("noa1,noa2")); + assertThat(nonOptionArgs).isEqualTo("noa1,noa2"); } @Test @@ -170,7 +167,7 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--o1=VAL_1"); PropertySource ps = new JOptCommandLinePropertySource(options); - assertThat(ps.getProperty("o1"), equalTo("VAL_1")); + assertThat(ps.getProperty("o1")).isEqualTo("VAL_1"); } public static enum OptionEnum { diff --git a/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java b/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java index aef17995be..bee1a02a0d 100644 --- a/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java @@ -22,14 +22,9 @@ import org.junit.Test; import org.springframework.mock.env.MockPropertySource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -48,68 +43,68 @@ public class MutablePropertySourcesTests { sources.addLast(new MockPropertySource("d").withProperty("p1", "dValue")); sources.addLast(new MockPropertySource("f").withProperty("p1", "fValue")); - assertThat(sources.size(), equalTo(3)); - assertThat(sources.contains("a"), is(false)); - assertThat(sources.contains("b"), is(true)); - assertThat(sources.contains("c"), is(false)); - assertThat(sources.contains("d"), is(true)); - assertThat(sources.contains("e"), is(false)); - assertThat(sources.contains("f"), is(true)); - assertThat(sources.contains("g"), is(false)); + assertThat(sources.size()).isEqualTo(3); + assertThat(sources.contains("a")).isFalse(); + assertThat(sources.contains("b")).isTrue(); + assertThat(sources.contains("c")).isFalse(); + assertThat(sources.contains("d")).isTrue(); + assertThat(sources.contains("e")).isFalse(); + assertThat(sources.contains("f")).isTrue(); + assertThat(sources.contains("g")).isFalse(); - assertThat(sources.get("b"), not(nullValue())); - assertThat(sources.get("b").getProperty("p1"), equalTo("bValue")); - assertThat(sources.get("d"), not(nullValue())); - assertThat(sources.get("d").getProperty("p1"), equalTo("dValue")); + assertThat(sources.get("b")).isNotNull(); + assertThat(sources.get("b").getProperty("p1")).isEqualTo("bValue"); + assertThat(sources.get("d")).isNotNull(); + assertThat(sources.get("d").getProperty("p1")).isEqualTo("dValue"); sources.addBefore("b", new MockPropertySource("a")); sources.addAfter("b", new MockPropertySource("c")); - assertThat(sources.size(), equalTo(5)); - assertThat(sources.precedenceOf(PropertySource.named("a")), is(0)); - assertThat(sources.precedenceOf(PropertySource.named("b")), is(1)); - assertThat(sources.precedenceOf(PropertySource.named("c")), is(2)); - assertThat(sources.precedenceOf(PropertySource.named("d")), is(3)); - assertThat(sources.precedenceOf(PropertySource.named("f")), is(4)); + assertThat(sources.size()).isEqualTo(5); + assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1); + assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2); + assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(3); + assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(4); sources.addBefore("f", new MockPropertySource("e")); sources.addAfter("f", new MockPropertySource("g")); - assertThat(sources.size(), equalTo(7)); - assertThat(sources.precedenceOf(PropertySource.named("a")), is(0)); - assertThat(sources.precedenceOf(PropertySource.named("b")), is(1)); - assertThat(sources.precedenceOf(PropertySource.named("c")), is(2)); - assertThat(sources.precedenceOf(PropertySource.named("d")), is(3)); - assertThat(sources.precedenceOf(PropertySource.named("e")), is(4)); - assertThat(sources.precedenceOf(PropertySource.named("f")), is(5)); - assertThat(sources.precedenceOf(PropertySource.named("g")), is(6)); + assertThat(sources.size()).isEqualTo(7); + assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1); + assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2); + assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(3); + assertThat(sources.precedenceOf(PropertySource.named("e"))).isEqualTo(4); + assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(5); + assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(6); sources.addLast(new MockPropertySource("a")); - assertThat(sources.size(), equalTo(7)); - assertThat(sources.precedenceOf(PropertySource.named("b")), is(0)); - assertThat(sources.precedenceOf(PropertySource.named("c")), is(1)); - assertThat(sources.precedenceOf(PropertySource.named("d")), is(2)); - assertThat(sources.precedenceOf(PropertySource.named("e")), is(3)); - assertThat(sources.precedenceOf(PropertySource.named("f")), is(4)); - assertThat(sources.precedenceOf(PropertySource.named("g")), is(5)); - assertThat(sources.precedenceOf(PropertySource.named("a")), is(6)); + assertThat(sources.size()).isEqualTo(7); + assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(1); + assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(2); + assertThat(sources.precedenceOf(PropertySource.named("e"))).isEqualTo(3); + assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(4); + assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(5); + assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(6); sources.addFirst(new MockPropertySource("a")); - assertThat(sources.size(), equalTo(7)); - assertThat(sources.precedenceOf(PropertySource.named("a")), is(0)); - assertThat(sources.precedenceOf(PropertySource.named("b")), is(1)); - assertThat(sources.precedenceOf(PropertySource.named("c")), is(2)); - assertThat(sources.precedenceOf(PropertySource.named("d")), is(3)); - assertThat(sources.precedenceOf(PropertySource.named("e")), is(4)); - assertThat(sources.precedenceOf(PropertySource.named("f")), is(5)); - assertThat(sources.precedenceOf(PropertySource.named("g")), is(6)); + assertThat(sources.size()).isEqualTo(7); + assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1); + assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2); + assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(3); + assertThat(sources.precedenceOf(PropertySource.named("e"))).isEqualTo(4); + assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(5); + assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(6); assertEquals(sources.remove("a"), PropertySource.named("a")); - assertThat(sources.size(), equalTo(6)); - assertThat(sources.contains("a"), is(false)); + assertThat(sources.size()).isEqualTo(6); + assertThat(sources.contains("a")).isFalse(); assertNull(sources.remove("a")); - assertThat(sources.size(), equalTo(6)); + assertThat(sources.size()).isEqualTo(6); String bogusPS = "bogus"; assertThatIllegalArgumentException().isThrownBy(() -> @@ -117,16 +112,16 @@ public class MutablePropertySourcesTests { .withMessageContaining("does not exist"); sources.addFirst(new MockPropertySource("a")); - assertThat(sources.size(), equalTo(7)); - assertThat(sources.precedenceOf(PropertySource.named("a")), is(0)); - assertThat(sources.precedenceOf(PropertySource.named("b")), is(1)); - assertThat(sources.precedenceOf(PropertySource.named("c")), is(2)); + assertThat(sources.size()).isEqualTo(7); + assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1); + assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2); sources.replace("a", new MockPropertySource("a-replaced")); - assertThat(sources.size(), equalTo(7)); - assertThat(sources.precedenceOf(PropertySource.named("a-replaced")), is(0)); - assertThat(sources.precedenceOf(PropertySource.named("b")), is(1)); - assertThat(sources.precedenceOf(PropertySource.named("c")), is(2)); + assertThat(sources.size()).isEqualTo(7); + assertThat(sources.precedenceOf(PropertySource.named("a-replaced"))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1); + assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2); sources.replace("a-replaced", new MockPropertySource("a")); @@ -146,7 +141,7 @@ public class MutablePropertySourcesTests { @Test public void getNonExistentPropertySourceReturnsNull() { MutablePropertySources sources = new MutablePropertySources(); - assertThat(sources.get("bogus"), nullValue()); + assertThat(sources.get("bogus")).isNull(); } @Test @@ -175,17 +170,17 @@ public class MutablePropertySourcesTests { MutablePropertySources sources = new MutablePropertySources(); sources.addLast(new MockPropertySource("test")); - assertThat(sources.stream(), notNullValue()); - assertThat(sources.stream().count(), is(1L)); - assertThat(sources.stream().anyMatch(source -> "test".equals(source.getName())), is(true)); - assertThat(sources.stream().anyMatch(source -> "bogus".equals(source.getName())), is(false)); + assertThat(sources.stream()).isNotNull(); + assertThat(sources.stream().count()).isEqualTo(1L); + assertThat(sources.stream().anyMatch(source -> "test".equals(source.getName()))).isTrue(); + assertThat(sources.stream().anyMatch(source -> "bogus".equals(source.getName()))).isFalse(); } @Test public void streamIsEmptyForEmptySources() { MutablePropertySources sources = new MutablePropertySources(); - assertThat(sources.stream(), notNullValue()); - assertThat(sources.stream().count(), is(0L)); + assertThat(sources.stream()).isNotNull(); + assertThat(sources.stream().count()).isEqualTo(0L); } } diff --git a/spring-core/src/test/java/org/springframework/core/env/PropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/PropertySourceTests.java index 70d17f558f..3290b0ad92 100644 --- a/spring-core/src/test/java/org/springframework/core/env/PropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/PropertySourceTests.java @@ -24,9 +24,8 @@ import java.util.Properties; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link PropertySource} implementations. @@ -53,19 +52,19 @@ public class PropertySourceTests { }}; MapPropertySource mps = new MapPropertySource("mps", map1); - assertThat(mps, equalTo(mps)); + assertThat(mps).isEqualTo(mps); - assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map1)), is(true)); - assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map2)), is(true)); - assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props1)), is(true)); - assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props2)), is(true)); + assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map1))).isTrue(); + assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map2))).isTrue(); + assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props1))).isTrue(); + assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props2))).isTrue(); - assertThat(new MapPropertySource("x", map1).equals(new Object()), is(false)); - assertThat(new MapPropertySource("x", map1).equals("x"), is(false)); - assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map1)), is(false)); - assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map2)), is(false)); - assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props1)), is(false)); - assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props2)), is(false)); + assertThat(new MapPropertySource("x", map1).equals(new Object())).isFalse(); + assertThat(new MapPropertySource("x", map1).equals("x")).isFalse(); + assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map1))).isFalse(); + assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map2))).isFalse(); + assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props1))).isFalse(); + assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props2))).isFalse(); } @Test @@ -81,23 +80,23 @@ public class PropertySourceTests { PropertySource ps1 = new MapPropertySource("ps1", map1); ps1.getSource(); List> propertySources = new ArrayList<>(); - assertThat(propertySources.add(ps1), equalTo(true)); - assertThat(propertySources.contains(ps1), is(true)); - assertThat(propertySources.contains(PropertySource.named("ps1")), is(true)); + assertThat(propertySources.add(ps1)).isEqualTo(true); + assertThat(propertySources.contains(ps1)).isTrue(); + assertThat(propertySources.contains(PropertySource.named("ps1"))).isTrue(); PropertySource ps1replacement = new MapPropertySource("ps1", map2); // notice - different map - assertThat(propertySources.add(ps1replacement), is(true)); // true because linkedlist allows duplicates - assertThat(propertySources.size(), is(2)); - assertThat(propertySources.remove(PropertySource.named("ps1")), is(true)); - assertThat(propertySources.size(), is(1)); - assertThat(propertySources.remove(PropertySource.named("ps1")), is(true)); - assertThat(propertySources.size(), is(0)); + assertThat(propertySources.add(ps1replacement)).isTrue(); // true because linkedlist allows duplicates + assertThat(propertySources).hasSize(2); + assertThat(propertySources.remove(PropertySource.named("ps1"))).isTrue(); + assertThat(propertySources).hasSize(1); + assertThat(propertySources.remove(PropertySource.named("ps1"))).isTrue(); + assertThat(propertySources).hasSize(0); PropertySource ps2 = new MapPropertySource("ps2", map2); propertySources.add(ps1); propertySources.add(ps2); - assertThat(propertySources.indexOf(PropertySource.named("ps1")), is(0)); - assertThat(propertySources.indexOf(PropertySource.named("ps2")), is(1)); + assertThat(propertySources.indexOf(PropertySource.named("ps1"))).isEqualTo(0); + assertThat(propertySources.indexOf(PropertySource.named("ps2"))).isEqualTo(1); propertySources.clear(); } diff --git a/spring-core/src/test/java/org/springframework/core/env/PropertySourcesPropertyResolverTests.java b/spring-core/src/test/java/org/springframework/core/env/PropertySourcesPropertyResolverTests.java index 6fc874bba4..6a665d9429 100644 --- a/spring-core/src/test/java/org/springframework/core/env/PropertySourcesPropertyResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/PropertySourcesPropertyResolverTests.java @@ -26,15 +26,10 @@ import org.junit.Test; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.mock.env.MockPropertySource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertTrue; /** * @author Chris Beams @@ -60,23 +55,23 @@ public class PropertySourcesPropertyResolverTests { @Test public void containsProperty() { - assertThat(propertyResolver.containsProperty("foo"), is(false)); + assertThat(propertyResolver.containsProperty("foo")).isFalse(); testProperties.put("foo", "bar"); - assertThat(propertyResolver.containsProperty("foo"), is(true)); + assertThat(propertyResolver.containsProperty("foo")).isTrue(); } @Test public void getProperty() { - assertThat(propertyResolver.getProperty("foo"), nullValue()); + assertThat(propertyResolver.getProperty("foo")).isNull(); testProperties.put("foo", "bar"); - assertThat(propertyResolver.getProperty("foo"), is("bar")); + assertThat(propertyResolver.getProperty("foo")).isEqualTo("bar"); } @Test public void getProperty_withDefaultValue() { - assertThat(propertyResolver.getProperty("foo", "myDefault"), is("myDefault")); + assertThat(propertyResolver.getProperty("foo", "myDefault")).isEqualTo("myDefault"); testProperties.put("foo", "bar"); - assertThat(propertyResolver.getProperty("foo"), is("bar")); + assertThat(propertyResolver.getProperty("foo")).isEqualTo("bar"); } @Test @@ -84,11 +79,11 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources sources = new MutablePropertySources(); PropertyResolver resolver = new PropertySourcesPropertyResolver(sources); sources.addFirst(new MockPropertySource("ps1").withProperty("pName", "ps1Value")); - assertThat(resolver.getProperty("pName"), equalTo("ps1Value")); + assertThat(resolver.getProperty("pName")).isEqualTo("ps1Value"); sources.addFirst(new MockPropertySource("ps2").withProperty("pName", "ps2Value")); - assertThat(resolver.getProperty("pName"), equalTo("ps2Value")); + assertThat(resolver.getProperty("pName")).isEqualTo("ps2Value"); sources.addFirst(new MockPropertySource("ps3").withProperty("pName", "ps3Value")); - assertThat(resolver.getProperty("pName"), equalTo("ps3Value")); + assertThat(resolver.getProperty("pName")).isEqualTo("ps3Value"); } @Test @@ -97,20 +92,20 @@ public class PropertySourcesPropertyResolverTests { Map nullableProperties = new HashMap<>(); propertySources.addLast(new MapPropertySource("nullableProperties", nullableProperties)); nullableProperties.put("foo", null); - assertThat(propertyResolver.getProperty("foo"), nullValue()); + assertThat(propertyResolver.getProperty("foo")).isNull(); } @Test public void getProperty_withTargetType_andDefaultValue() { - assertThat(propertyResolver.getProperty("foo", Integer.class, 42), equalTo(42)); + assertThat(propertyResolver.getProperty("foo", Integer.class, 42)).isEqualTo(42); testProperties.put("foo", 13); - assertThat(propertyResolver.getProperty("foo", Integer.class, 42), equalTo(13)); + assertThat(propertyResolver.getProperty("foo", Integer.class, 42)).isEqualTo(13); } @Test public void getProperty_withStringArrayConversion() { testProperties.put("foo", "bar,baz"); - assertThat(propertyResolver.getProperty("foo", String[].class), equalTo(new String[] { "bar", "baz" })); + assertThat(propertyResolver.getProperty("foo", String[].class)).isEqualTo(new String[] { "bar", "baz" }); } @Test @@ -134,9 +129,9 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MapPropertySource("testProperties", map)); PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(propertyResolver.getProperty(key), equalTo(value1)); + assertThat(propertyResolver.getProperty(key)).isEqualTo(value1); map.put(key, value2); // after construction and first resolution - assertThat(propertyResolver.getProperty(key), equalTo(value2)); + assertThat(propertyResolver.getProperty(key)).isEqualTo(value2); } @Test @@ -145,9 +140,9 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MapPropertySource("testProperties", map)); PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(propertyResolver.getProperty("foo"), equalTo(null)); + assertThat(propertyResolver.getProperty("foo")).isNull(); map.put("foo", "42"); - assertThat(propertyResolver.getProperty("foo"), equalTo("42")); + assertThat(propertyResolver.getProperty("foo")).isEqualTo("42"); } @Test @@ -158,21 +153,21 @@ public class PropertySourcesPropertyResolverTests { propertySources.addLast(new MockPropertySource("system").withProperty("foo", "systemValue")); // 'local' was added first so has precedence - assertThat(propertyResolver.getProperty("foo"), equalTo("localValue")); + assertThat(propertyResolver.getProperty("foo")).isEqualTo("localValue"); // replace 'local' with new property source propertySources.replace("local", new MockPropertySource("new").withProperty("foo", "newValue")); // 'system' now has precedence - assertThat(propertyResolver.getProperty("foo"), equalTo("newValue")); + assertThat(propertyResolver.getProperty("foo")).isEqualTo("newValue"); - assertThat(propertySources.size(), is(2)); + assertThat(propertySources).hasSize(2); } @Test public void getRequiredProperty() { testProperties.put("exists", "xyz"); - assertThat(propertyResolver.getRequiredProperty("exists"), is("xyz")); + assertThat(propertyResolver.getRequiredProperty("exists")).isEqualTo("xyz"); assertThatIllegalStateException().isThrownBy(() -> propertyResolver.getRequiredProperty("bogus")); @@ -181,7 +176,7 @@ public class PropertySourcesPropertyResolverTests { @Test public void getRequiredProperty_withStringArrayConversion() { testProperties.put("exists", "abc,123"); - assertThat(propertyResolver.getRequiredProperty("exists", String[].class), equalTo(new String[] { "abc", "123" })); + assertThat(propertyResolver.getRequiredProperty("exists", String[].class)).isEqualTo(new String[] { "abc", "123" }); assertThatIllegalStateException().isThrownBy(() -> propertyResolver.getRequiredProperty("bogus", String[].class)); @@ -192,7 +187,7 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("key", "value")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(resolver.resolvePlaceholders("Replace this ${key}"), equalTo("Replace this value")); + assertThat(resolver.resolvePlaceholders("Replace this ${key}")).isEqualTo("Replace this value"); } @Test @@ -200,8 +195,8 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("key", "value")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown}"), - equalTo("Replace this value plus ${unknown}")); + assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown}")) + .isEqualTo("Replace this value plus ${unknown}"); } @Test @@ -209,8 +204,8 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("key", "value")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown:defaultValue}"), - equalTo("Replace this value plus defaultValue")); + assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown:defaultValue}")) + .isEqualTo("Replace this value plus defaultValue"); } @Test @@ -224,7 +219,7 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("key", "value")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key}"), equalTo("Replace this value")); + assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key}")).isEqualTo("Replace this value"); } @Test @@ -241,8 +236,8 @@ public class PropertySourcesPropertyResolverTests { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("key", "value")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); - assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown:defaultValue}"), - equalTo("Replace this value plus defaultValue")); + assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown:defaultValue}")) + .isEqualTo("Replace this value plus defaultValue"); } @Test @@ -291,24 +286,17 @@ public class PropertySourcesPropertyResolverTests { .withProperty("pR", "${pL}") // cyclic reference right ); ConfigurablePropertyResolver pr = new PropertySourcesPropertyResolver(ps); - assertThat(pr.getProperty("p1"), equalTo("v1")); - assertThat(pr.getProperty("p2"), equalTo("v2")); - assertThat(pr.getProperty("p3"), equalTo("v1:v2")); - assertThat(pr.getProperty("p4"), equalTo("v1:v2")); - try { - pr.getProperty("p5"); - } - catch (IllegalArgumentException ex) { - assertThat(ex.getMessage(), containsString( - "Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\"")); - } - assertThat(pr.getProperty("p6"), equalTo("v1:v2:def")); - try { - pr.getProperty("pL"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().toLowerCase().contains("circular")); - } + assertThat(pr.getProperty("p1")).isEqualTo("v1"); + assertThat(pr.getProperty("p2")).isEqualTo("v2"); + assertThat(pr.getProperty("p3")).isEqualTo("v1:v2"); + assertThat(pr.getProperty("p4")).isEqualTo("v1:v2"); + assertThatIllegalArgumentException().isThrownBy(() -> + pr.getProperty("p5")) + .withMessageContaining("Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\""); + assertThat(pr.getProperty("p6")).isEqualTo("v1:v2:def"); + assertThatIllegalArgumentException().isThrownBy(() -> + pr.getProperty("pL")) + .withMessageContaining("Circular"); } @Test @@ -321,35 +309,27 @@ public class PropertySourcesPropertyResolverTests { .withProperty("p4", "${p1}:${p2}:${bogus}") // unresolvable placeholder ); ConfigurablePropertyResolver pr = new PropertySourcesPropertyResolver(ps); - assertThat(pr.getProperty("p1"), equalTo("v1")); - assertThat(pr.getProperty("p2"), equalTo("v2")); - assertThat(pr.getProperty("p3"), equalTo("v1:v2:def")); + assertThat(pr.getProperty("p1")).isEqualTo("v1"); + assertThat(pr.getProperty("p2")).isEqualTo("v2"); + assertThat(pr.getProperty("p3")).isEqualTo("v1:v2:def"); // placeholders nested within the value of "p4" are unresolvable and cause an // exception by default - try { - pr.getProperty("p4"); - } - catch (IllegalArgumentException ex) { - assertThat(ex.getMessage(), containsString( - "Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\"")); - } + assertThatIllegalArgumentException().isThrownBy(() -> + pr.getProperty("p4")) + .withMessageContaining("Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\""); // relax the treatment of unresolvable nested placeholders pr.setIgnoreUnresolvableNestedPlaceholders(true); // and observe they now pass through unresolved - assertThat(pr.getProperty("p4"), equalTo("v1:v2:${bogus}")); + assertThat(pr.getProperty("p4")).isEqualTo("v1:v2:${bogus}"); // resolve[Nested]Placeholders methods behave as usual regardless the value of // ignoreUnresolvableNestedPlaceholders - assertThat(pr.resolvePlaceholders("${p1}:${p2}:${bogus}"), equalTo("v1:v2:${bogus}")); - try { - pr.resolveRequiredPlaceholders("${p1}:${p2}:${bogus}"); - } - catch (IllegalArgumentException ex) { - assertThat(ex.getMessage(), containsString( - "Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\"")); - } + assertThat(pr.resolvePlaceholders("${p1}:${p2}:${bogus}")).isEqualTo("v1:v2:${bogus}"); + assertThatIllegalArgumentException().isThrownBy(() -> + pr.resolveRequiredPlaceholders("${p1}:${p2}:${bogus}")) + .withMessageContaining("Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\""); } } diff --git a/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLineParserTests.java b/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLineParserTests.java index dd5bab2cde..e87ffb1c59 100644 --- a/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLineParserTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLineParserTests.java @@ -21,47 +21,45 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; + public class SimpleCommandLineParserTests { @Test public void withNoOptions() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); - assertThat(parser.parse().getOptionValues("foo"), nullValue()); + assertThat(parser.parse().getOptionValues("foo")).isNull(); } @Test public void withSingleOptionAndNoValue() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); CommandLineArgs args = parser.parse("--o1"); - assertThat(args.containsOption("o1"), is(true)); - assertThat(args.getOptionValues("o1"), equalTo(Collections.EMPTY_LIST)); + assertThat(args.containsOption("o1")).isTrue(); + assertThat(args.getOptionValues("o1")).isEqualTo(Collections.EMPTY_LIST); } @Test public void withSingleOptionAndValue() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); CommandLineArgs args = parser.parse("--o1=v1"); - assertThat(args.containsOption("o1"), is(true)); - assertThat(args.getOptionValues("o1").get(0), equalTo("v1")); + assertThat(args.containsOption("o1")).isTrue(); + assertThat(args.getOptionValues("o1").get(0)).isEqualTo("v1"); } @Test public void withMixOfOptionsHavingValueAndOptionsHavingNoValue() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); CommandLineArgs args = parser.parse("--o1=v1", "--o2"); - assertThat(args.containsOption("o1"), is(true)); - assertThat(args.containsOption("o2"), is(true)); - assertThat(args.containsOption("o3"), is(false)); - assertThat(args.getOptionValues("o1").get(0), equalTo("v1")); - assertThat(args.getOptionValues("o2"), equalTo(Collections.EMPTY_LIST)); - assertThat(args.getOptionValues("o3"), nullValue()); + assertThat(args.containsOption("o1")).isTrue(); + assertThat(args.containsOption("o2")).isTrue(); + assertThat(args.containsOption("o3")).isFalse(); + assertThat(args.getOptionValues("o1").get(0)).isEqualTo("v1"); + assertThat(args.getOptionValues("o2")).isEqualTo(Collections.EMPTY_LIST); + assertThat(args.getOptionValues("o3")).isNull(); } @Test @@ -96,13 +94,13 @@ public class SimpleCommandLineParserTests { public void withNonOptionArguments() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); CommandLineArgs args = parser.parse("--o1=v1", "noa1", "--o2=v2", "noa2"); - assertThat(args.getOptionValues("o1").get(0), equalTo("v1")); - assertThat(args.getOptionValues("o2").get(0), equalTo("v2")); + assertThat(args.getOptionValues("o1").get(0)).isEqualTo("v1"); + assertThat(args.getOptionValues("o2").get(0)).isEqualTo("v2"); List nonOptions = args.getNonOptionArgs(); - assertThat(nonOptions.get(0), equalTo("noa1")); - assertThat(nonOptions.get(1), equalTo("noa2")); - assertThat(nonOptions.size(), equalTo(2)); + assertThat(nonOptions.get(0)).isEqualTo("noa1"); + assertThat(nonOptions.get(1)).isEqualTo("noa2"); + assertThat(nonOptions.size()).isEqualTo(2); } @Test 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 c66db31250..fbc22ee87a 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 @@ -20,10 +20,8 @@ import java.util.List; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link SimpleCommandLinePropertySource}. @@ -36,46 +34,46 @@ public class SimpleCommandLinePropertySourceTests { @Test public void withDefaultName() { PropertySource ps = new SimpleCommandLinePropertySource(); - assertThat(ps.getName(), - equalTo(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)); + assertThat(ps.getName()) + .isEqualTo(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME); } @Test public void withCustomName() { PropertySource ps = new SimpleCommandLinePropertySource("ps1", new String[0]); - assertThat(ps.getName(), equalTo("ps1")); + assertThat(ps.getName()).isEqualTo("ps1"); } @Test public void withNoArgs() { PropertySource ps = new SimpleCommandLinePropertySource(); - assertThat(ps.containsProperty("foo"), is(false)); - assertThat(ps.getProperty("foo"), nullValue()); + assertThat(ps.containsProperty("foo")).isFalse(); + assertThat(ps.getProperty("foo")).isNull(); } @Test public void withOptionArgsOnly() { CommandLinePropertySource ps = new SimpleCommandLinePropertySource("--o1=v1", "--o2"); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); - assertThat(ps.containsProperty("o3"), is(false)); - assertThat(ps.getProperty("o1"), equalTo("v1")); - assertThat(ps.getProperty("o2"), equalTo("")); - assertThat(ps.getProperty("o3"), nullValue()); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); + assertThat(ps.containsProperty("o3")).isFalse(); + assertThat(ps.getProperty("o1")).isEqualTo("v1"); + assertThat(ps.getProperty("o2")).isEqualTo(""); + assertThat(ps.getProperty("o3")).isNull(); } @Test public void withDefaultNonOptionArgsNameAndNoNonOptionArgsPresent() { EnumerablePropertySource ps = new SimpleCommandLinePropertySource("--o1=v1", "--o2"); - assertThat(ps.containsProperty("nonOptionArgs"), is(false)); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("nonOptionArgs")).isFalse(); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); - assertThat(ps.containsProperty("nonOptionArgs"), is(false)); - assertThat(ps.getProperty("nonOptionArgs"), nullValue()); - assertThat(ps.getPropertyNames().length, is(2)); + assertThat(ps.containsProperty("nonOptionArgs")).isFalse(); + assertThat(ps.getProperty("nonOptionArgs")).isNull(); + assertThat(ps.getPropertyNames().length).isEqualTo(2); } @Test @@ -83,12 +81,12 @@ public class SimpleCommandLinePropertySourceTests { CommandLinePropertySource ps = new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2"); - assertThat(ps.containsProperty("nonOptionArgs"), is(true)); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("nonOptionArgs")).isTrue(); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); String nonOptionArgs = ps.getProperty("nonOptionArgs"); - assertThat(nonOptionArgs, equalTo("noa1,noa2")); + assertThat(nonOptionArgs).isEqualTo("noa1,noa2"); } @Test @@ -97,12 +95,12 @@ public class SimpleCommandLinePropertySourceTests { new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2"); ps.setNonOptionArgsPropertyName("NOA"); - assertThat(ps.containsProperty("nonOptionArgs"), is(false)); - assertThat(ps.containsProperty("NOA"), is(true)); - assertThat(ps.containsProperty("o1"), is(true)); - assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("nonOptionArgs")).isFalse(); + assertThat(ps.containsProperty("NOA")).isTrue(); + assertThat(ps.containsProperty("o1")).isTrue(); + assertThat(ps.containsProperty("o2")).isTrue(); String nonOptionArgs = ps.getProperty("NOA"); - assertThat(nonOptionArgs, equalTo("noa1,noa2")); + assertThat(nonOptionArgs).isEqualTo("noa1,noa2"); } @Test @@ -113,16 +111,16 @@ public class SimpleCommandLinePropertySourceTests { env.getPropertySources().addFirst(ps); String nonOptionArgs = env.getProperty("nonOptionArgs"); - assertThat(nonOptionArgs, equalTo("noa1,noa2")); + assertThat(nonOptionArgs).isEqualTo("noa1,noa2"); String[] nonOptionArgsArray = env.getProperty("nonOptionArgs", String[].class); - assertThat(nonOptionArgsArray[0], equalTo("noa1")); - assertThat(nonOptionArgsArray[1], equalTo("noa2")); + assertThat(nonOptionArgsArray[0]).isEqualTo("noa1"); + assertThat(nonOptionArgsArray[1]).isEqualTo("noa2"); @SuppressWarnings("unchecked") List nonOptionArgsList = env.getProperty("nonOptionArgs", List.class); - assertThat(nonOptionArgsList.get(0), equalTo("noa1")); - assertThat(nonOptionArgsList.get(1), equalTo("noa2")); + assertThat(nonOptionArgsList.get(0)).isEqualTo("noa1"); + assertThat(nonOptionArgsList.get(1)).isEqualTo("noa2"); } } diff --git a/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java b/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java index 294e2f45fa..bdca552361 100644 --- a/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java @@ -28,17 +28,8 @@ import org.junit.Test; import org.springframework.core.SpringProperties; import org.springframework.mock.env.MockPropertySource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME; @@ -84,64 +75,64 @@ public class StandardEnvironmentTests { .withProperty("parentKey", "parentVal") .withProperty("bothKey", "parentBothVal")); - assertThat(child.getProperty("childKey"), is("childVal")); - assertThat(child.getProperty("parentKey"), nullValue()); - assertThat(child.getProperty("bothKey"), is("childBothVal")); + assertThat(child.getProperty("childKey")).isEqualTo("childVal"); + assertThat(child.getProperty("parentKey")).isNull(); + assertThat(child.getProperty("bothKey")).isEqualTo("childBothVal"); - assertThat(parent.getProperty("childKey"), nullValue()); - assertThat(parent.getProperty("parentKey"), is("parentVal")); - assertThat(parent.getProperty("bothKey"), is("parentBothVal")); + assertThat(parent.getProperty("childKey")).isNull(); + assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal"); + assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal"); - assertThat(child.getActiveProfiles(), equalTo(new String[]{"c1","c2"})); - assertThat(parent.getActiveProfiles(), equalTo(new String[]{"p1","p2"})); + assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2"}); + assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"}); child.merge(parent); - assertThat(child.getProperty("childKey"), is("childVal")); - assertThat(child.getProperty("parentKey"), is("parentVal")); - assertThat(child.getProperty("bothKey"), is("childBothVal")); + assertThat(child.getProperty("childKey")).isEqualTo("childVal"); + assertThat(child.getProperty("parentKey")).isEqualTo("parentVal"); + assertThat(child.getProperty("bothKey")).isEqualTo("childBothVal"); - assertThat(parent.getProperty("childKey"), nullValue()); - assertThat(parent.getProperty("parentKey"), is("parentVal")); - assertThat(parent.getProperty("bothKey"), is("parentBothVal")); + assertThat(parent.getProperty("childKey")).isNull(); + assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal"); + assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal"); - assertThat(child.getActiveProfiles(), equalTo(new String[]{"c1","c2","p1","p2"})); - assertThat(parent.getActiveProfiles(), equalTo(new String[]{"p1","p2"})); + assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2","p1","p2"}); + assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"}); } @Test public void propertySourceOrder() { ConfigurableEnvironment env = new StandardEnvironment(); MutablePropertySources sources = env.getPropertySources(); - assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(0)); - assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(1)); - assertThat(sources.size(), is(2)); + assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))).isEqualTo(0); + assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))).isEqualTo(1); + assertThat(sources).hasSize(2); } @Test public void propertySourceTypes() { ConfigurableEnvironment env = new StandardEnvironment(); MutablePropertySources sources = env.getPropertySources(); - assertThat(sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME), instanceOf(SystemEnvironmentPropertySource.class)); + assertThat(sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isInstanceOf(SystemEnvironmentPropertySource.class); } @Test public void activeProfilesIsEmptyByDefault() { - assertThat(environment.getActiveProfiles().length, is(0)); + assertThat(environment.getActiveProfiles().length).isEqualTo(0); } @Test public void defaultProfilesContainsDefaultProfileByDefault() { - assertThat(environment.getDefaultProfiles().length, is(1)); - assertThat(environment.getDefaultProfiles()[0], equalTo("default")); + assertThat(environment.getDefaultProfiles().length).isEqualTo(1); + assertThat(environment.getDefaultProfiles()[0]).isEqualTo("default"); } @Test public void setActiveProfiles() { environment.setActiveProfiles("local", "embedded"); String[] activeProfiles = environment.getActiveProfiles(); - assertThat(Arrays.asList(activeProfiles), hasItems("local", "embedded")); - assertThat(activeProfiles.length, is(2)); + assertThat(activeProfiles).contains("local", "embedded"); + assertThat(activeProfiles.length).isEqualTo(2); } @Test @@ -194,36 +185,36 @@ public class StandardEnvironmentTests { @Test public void addActiveProfile() { - assertThat(environment.getActiveProfiles().length, is(0)); + assertThat(environment.getActiveProfiles().length).isEqualTo(0); environment.setActiveProfiles("local", "embedded"); - assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("local", "embedded")); - assertThat(environment.getActiveProfiles().length, is(2)); + assertThat(environment.getActiveProfiles()).contains("local", "embedded"); + assertThat(environment.getActiveProfiles().length).isEqualTo(2); environment.addActiveProfile("p1"); - assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("p1")); - assertThat(environment.getActiveProfiles().length, is(3)); + assertThat(environment.getActiveProfiles()).contains("p1"); + assertThat(environment.getActiveProfiles().length).isEqualTo(3); environment.addActiveProfile("p2"); environment.addActiveProfile("p3"); - assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("p2", "p3")); - assertThat(environment.getActiveProfiles().length, is(5)); + assertThat(environment.getActiveProfiles()).contains("p2", "p3"); + assertThat(environment.getActiveProfiles().length).isEqualTo(5); } @Test public void addActiveProfile_whenActiveProfilesPropertyIsAlreadySet() { ConfigurableEnvironment env = new StandardEnvironment(); - assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME), nullValue()); + assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isNull(); env.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1")); - assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME), equalTo("p1")); + assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isEqualTo("p1"); env.addActiveProfile("p2"); - assertThat(env.getActiveProfiles(), arrayContaining("p1", "p2")); + assertThat(env.getActiveProfiles()).contains("p1", "p2"); } @Test public void reservedDefaultProfile() { - assertThat(environment.getDefaultProfiles(), equalTo(new String[]{RESERVED_DEFAULT_PROFILE_NAME})); + assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{RESERVED_DEFAULT_PROFILE_NAME}); System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "d0"); - assertThat(environment.getDefaultProfiles(), equalTo(new String[]{"d0"})); + assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d0"}); environment.setDefaultProfiles("d1", "d2"); - assertThat(environment.getDefaultProfiles(), equalTo(new String[]{"d1","d2"})); + assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d1","d2"}); System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME); } @@ -241,50 +232,50 @@ public class StandardEnvironmentTests { @Test public void getActiveProfiles_systemPropertiesEmpty() { - assertThat(environment.getActiveProfiles().length, is(0)); + assertThat(environment.getActiveProfiles().length).isEqualTo(0); System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, ""); - assertThat(environment.getActiveProfiles().length, is(0)); + assertThat(environment.getActiveProfiles().length).isEqualTo(0); System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME); } @Test public void getActiveProfiles_fromSystemProperties() { System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo"); - assertThat(Arrays.asList(environment.getActiveProfiles()), hasItem("foo")); + assertThat(Arrays.asList(environment.getActiveProfiles())).contains("foo"); System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME); } @Test public void getActiveProfiles_fromSystemProperties_withMultipleProfiles() { System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar"); - assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("foo", "bar")); + assertThat(environment.getActiveProfiles()).contains("foo", "bar"); System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME); } @Test public void getActiveProfiles_fromSystemProperties_withMulitpleProfiles_withWhitespace() { System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace - assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("bar", "baz")); + assertThat(environment.getActiveProfiles()).contains("bar", "baz"); System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME); } @Test public void getDefaultProfiles() { - assertThat(environment.getDefaultProfiles(), equalTo(new String[] {RESERVED_DEFAULT_PROFILE_NAME})); + assertThat(environment.getDefaultProfiles()).isEqualTo(new String[] {RESERVED_DEFAULT_PROFILE_NAME}); environment.getPropertySources().addFirst(new MockPropertySource().withProperty(DEFAULT_PROFILES_PROPERTY_NAME, "pd1")); - assertThat(environment.getDefaultProfiles().length, is(1)); - assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItem("pd1")); + assertThat(environment.getDefaultProfiles().length).isEqualTo(1); + assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1"); } @Test public void setDefaultProfiles() { environment.setDefaultProfiles(); - assertThat(environment.getDefaultProfiles().length, is(0)); + assertThat(environment.getDefaultProfiles().length).isEqualTo(0); environment.setDefaultProfiles("pd1"); - assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItem("pd1")); + assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1"); environment.setDefaultProfiles("pd2", "pd3"); - assertThat(Arrays.asList(environment.getDefaultProfiles()), not(hasItem("pd1"))); - assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItems("pd2", "pd3")); + assertThat(environment.getDefaultProfiles()).doesNotContain("pd1"); + assertThat(environment.getDefaultProfiles()).contains("pd2", "pd3"); } @Test @@ -313,39 +304,39 @@ public class StandardEnvironmentTests { @Test public void acceptsProfiles_activeProfileSetProgrammatically() { - assertThat(environment.acceptsProfiles("p1", "p2"), is(false)); + assertThat(environment.acceptsProfiles("p1", "p2")).isFalse(); environment.setActiveProfiles("p1"); - assertThat(environment.acceptsProfiles("p1", "p2"), is(true)); + assertThat(environment.acceptsProfiles("p1", "p2")).isTrue(); environment.setActiveProfiles("p2"); - assertThat(environment.acceptsProfiles("p1", "p2"), is(true)); + assertThat(environment.acceptsProfiles("p1", "p2")).isTrue(); environment.setActiveProfiles("p1", "p2"); - assertThat(environment.acceptsProfiles("p1", "p2"), is(true)); + assertThat(environment.acceptsProfiles("p1", "p2")).isTrue(); } @Test public void acceptsProfiles_activeProfileSetViaProperty() { - assertThat(environment.acceptsProfiles("p1"), is(false)); + assertThat(environment.acceptsProfiles("p1")).isFalse(); environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1")); - assertThat(environment.acceptsProfiles("p1"), is(true)); + assertThat(environment.acceptsProfiles("p1")).isTrue(); } @Test public void acceptsProfiles_defaultProfile() { - assertThat(environment.acceptsProfiles("pd"), is(false)); + assertThat(environment.acceptsProfiles("pd")).isFalse(); environment.setDefaultProfiles("pd"); - assertThat(environment.acceptsProfiles("pd"), is(true)); + assertThat(environment.acceptsProfiles("pd")).isTrue(); environment.setActiveProfiles("p1"); - assertThat(environment.acceptsProfiles("pd"), is(false)); - assertThat(environment.acceptsProfiles("p1"), is(true)); + assertThat(environment.acceptsProfiles("pd")).isFalse(); + assertThat(environment.acceptsProfiles("p1")).isTrue(); } @Test public void acceptsProfiles_withNotOperator() { - assertThat(environment.acceptsProfiles("p1"), is(false)); - assertThat(environment.acceptsProfiles("!p1"), is(true)); + assertThat(environment.acceptsProfiles("p1")).isFalse(); + assertThat(environment.acceptsProfiles("!p1")).isTrue(); environment.addActiveProfile("p1"); - assertThat(environment.acceptsProfiles("p1"), is(true)); - assertThat(environment.acceptsProfiles("!p1"), is(false)); + assertThat(environment.acceptsProfiles("p1")).isTrue(); + assertThat(environment.acceptsProfiles("!p1")).isFalse(); } @Test @@ -356,11 +347,11 @@ public class StandardEnvironmentTests { @Test public void acceptsProfiles_withProfileExpression() { - assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2")), is(false)); + assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse(); environment.addActiveProfile("p1"); - assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2")), is(false)); + assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse(); environment.addActiveProfile("p2"); - assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2")), is(true)); + assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isTrue(); } @Test @@ -413,14 +404,14 @@ public class StandardEnvironmentTests { { Map systemProperties = environment.getSystemProperties(); - assertThat(systemProperties, notNullValue()); + assertThat(systemProperties).isNotNull(); assertSame(systemProperties, System.getProperties()); - assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME), equalTo((Object)ALLOWED_PROPERTY_VALUE)); - assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME), equalTo((Object)DISALLOWED_PROPERTY_VALUE)); + assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE); + assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE); // non-string keys and values work fine... until the security manager is introduced below - assertThat(systemProperties.get(STRING_PROPERTY_NAME), equalTo(NON_STRING_PROPERTY_VALUE)); - assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME), equalTo((Object)STRING_PROPERTY_VALUE)); + assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isEqualTo(NON_STRING_PROPERTY_VALUE); + assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME)).isEqualTo(STRING_PROPERTY_VALUE); } SecurityManager oldSecurityManager = System.getSecurityManager(); @@ -447,17 +438,17 @@ public class StandardEnvironmentTests { { Map systemProperties = environment.getSystemProperties(); - assertThat(systemProperties, notNullValue()); - assertThat(systemProperties, instanceOf(ReadOnlySystemAttributesMap.class)); - assertThat((String)systemProperties.get(ALLOWED_PROPERTY_NAME), equalTo(ALLOWED_PROPERTY_VALUE)); - assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME), equalTo(null)); + assertThat(systemProperties).isNotNull(); + assertThat(systemProperties).isInstanceOf(ReadOnlySystemAttributesMap.class); + assertThat((String)systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE); + assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isNull(); // nothing we can do here in terms of warning the user that there was // actually a (non-string) value available. By this point, we only // have access to calling System.getProperty(), which itself returns null // if the value is non-string. So we're stuck with returning a potentially // misleading null. - assertThat(systemProperties.get(STRING_PROPERTY_NAME), nullValue()); + assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isNull(); // in the case of a non-string *key*, however, we can do better. Alert // the user that under these very special conditions (non-object key + @@ -481,7 +472,7 @@ public class StandardEnvironmentTests { { Map systemEnvironment = environment.getSystemEnvironment(); - assertThat(systemEnvironment, notNullValue()); + assertThat(systemEnvironment).isNotNull(); assertSame(systemEnvironment, System.getenv()); } @@ -504,10 +495,10 @@ public class StandardEnvironmentTests { { Map systemEnvironment = environment.getSystemEnvironment(); - assertThat(systemEnvironment, notNullValue()); - assertThat(systemEnvironment, instanceOf(ReadOnlySystemAttributesMap.class)); - assertThat(systemEnvironment.get(ALLOWED_PROPERTY_NAME), equalTo((Object)ALLOWED_PROPERTY_VALUE)); - assertThat(systemEnvironment.get(DISALLOWED_PROPERTY_NAME), nullValue()); + assertThat(systemEnvironment).isNotNull(); + assertThat(systemEnvironment).isInstanceOf(ReadOnlySystemAttributesMap.class); + assertThat(systemEnvironment.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE); + assertThat(systemEnvironment.get(DISALLOWED_PROPERTY_NAME)).isNull(); } System.setSecurityManager(oldSecurityManager); diff --git a/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java index bdd045b6ee..9c411e8e51 100644 --- a/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java @@ -24,8 +24,8 @@ import java.util.Set; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link SystemEnvironmentPropertySource}. @@ -50,35 +50,35 @@ public class SystemEnvironmentPropertySourceTests { @Test public void none() { - assertThat(ps.containsProperty("a.key"), equalTo(false)); - assertThat(ps.getProperty("a.key"), equalTo(null)); + assertThat(ps.containsProperty("a.key")).isEqualTo(false); + assertThat(ps.getProperty("a.key")).isNull(); } @Test public void normalWithoutPeriod() { envMap.put("akey", "avalue"); - assertThat(ps.containsProperty("akey"), equalTo(true)); - assertThat(ps.getProperty("akey"), equalTo((Object)"avalue")); + assertThat(ps.containsProperty("akey")).isEqualTo(true); + assertThat(ps.getProperty("akey")).isEqualTo((Object)"avalue"); } @Test public void normalWithPeriod() { envMap.put("a.key", "a.value"); - assertThat(ps.containsProperty("a.key"), equalTo(true)); - assertThat(ps.getProperty("a.key"), equalTo((Object)"a.value")); + assertThat(ps.containsProperty("a.key")).isEqualTo(true); + assertThat(ps.getProperty("a.key")).isEqualTo((Object)"a.value"); } @Test public void withUnderscore() { envMap.put("a_key", "a_value"); - assertThat(ps.containsProperty("a_key"), equalTo(true)); - assertThat(ps.containsProperty("a.key"), equalTo(true)); + assertThat(ps.containsProperty("a_key")).isEqualTo(true); + assertThat(ps.containsProperty("a.key")).isEqualTo(true); - assertThat(ps.getProperty("a_key"), equalTo((Object)"a_value")); - assertThat( ps.getProperty("a.key"), equalTo((Object)"a_value")); + assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value"); + assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a_value"); } @Test @@ -86,8 +86,8 @@ public class SystemEnvironmentPropertySourceTests { envMap.put("a_key", "a_value"); envMap.put("a.key", "a.value"); - assertThat(ps.getProperty("a_key"), equalTo((Object)"a_value")); - assertThat( ps.getProperty("a.key"), equalTo((Object)"a.value")); + assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value"); + assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a.value"); } @Test @@ -97,55 +97,55 @@ public class SystemEnvironmentPropertySourceTests { envMap.put("A_DOT.KEY", "a_dot_value"); envMap.put("A_HYPHEN-KEY", "a_hyphen_value"); - assertThat(ps.containsProperty("A_KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-KEY"), equalTo(true)); - assertThat(ps.containsProperty("a_key"), equalTo(true)); - assertThat(ps.containsProperty("a.key"), equalTo(true)); - assertThat(ps.containsProperty("a-key"), equalTo(true)); - assertThat(ps.containsProperty("A_LONG_KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.LONG.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-LONG-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.LONG-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-LONG.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A_long_KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.long.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-long-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.long-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-long.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A_DOT.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-DOT.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A_dot.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A-dot.KEY"), equalTo(true)); - assertThat(ps.containsProperty("A_HYPHEN-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.HYPHEN-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A_hyphen-KEY"), equalTo(true)); - assertThat(ps.containsProperty("A.hyphen-KEY"), equalTo(true)); + assertThat(ps.containsProperty("A_KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("a_key")).isEqualTo(true); + assertThat(ps.containsProperty("a.key")).isEqualTo(true); + assertThat(ps.containsProperty("a-key")).isEqualTo(true); + assertThat(ps.containsProperty("A_LONG_KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.LONG.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-LONG-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.LONG-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-LONG.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A_long_KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.long.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-long-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.long-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-long.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A_DOT.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-DOT.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A_dot.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A-dot.KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A_HYPHEN-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.HYPHEN-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A_hyphen-KEY")).isEqualTo(true); + assertThat(ps.containsProperty("A.hyphen-KEY")).isEqualTo(true); - assertThat(ps.getProperty("A_KEY"), equalTo("a_value")); - assertThat(ps.getProperty("A.KEY"), equalTo("a_value")); - assertThat(ps.getProperty("A-KEY"), equalTo("a_value")); - assertThat(ps.getProperty("a_key"), equalTo("a_value")); - assertThat(ps.getProperty("a.key"), equalTo("a_value")); - assertThat(ps.getProperty("a-key"), equalTo("a_value")); - assertThat(ps.getProperty("A_LONG_KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A.LONG.KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A-LONG-KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A.LONG-KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A-LONG.KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A_long_KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A.long.KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A-long-KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A.long-KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A-long.KEY"), equalTo("a_long_value")); - assertThat(ps.getProperty("A_DOT.KEY"), equalTo("a_dot_value")); - assertThat(ps.getProperty("A-DOT.KEY"), equalTo("a_dot_value")); - assertThat(ps.getProperty("A_dot.KEY"), equalTo("a_dot_value")); - assertThat(ps.getProperty("A-dot.KEY"), equalTo("a_dot_value")); - assertThat(ps.getProperty("A_HYPHEN-KEY"), equalTo("a_hyphen_value")); - assertThat(ps.getProperty("A.HYPHEN-KEY"), equalTo("a_hyphen_value")); - assertThat(ps.getProperty("A_hyphen-KEY"), equalTo("a_hyphen_value")); - assertThat(ps.getProperty("A.hyphen-KEY"), equalTo("a_hyphen_value")); + assertThat(ps.getProperty("A_KEY")).isEqualTo("a_value"); + assertThat(ps.getProperty("A.KEY")).isEqualTo("a_value"); + assertThat(ps.getProperty("A-KEY")).isEqualTo("a_value"); + assertThat(ps.getProperty("a_key")).isEqualTo("a_value"); + assertThat(ps.getProperty("a.key")).isEqualTo("a_value"); + assertThat(ps.getProperty("a-key")).isEqualTo("a_value"); + assertThat(ps.getProperty("A_LONG_KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A.LONG.KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A-LONG-KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A.LONG-KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A-LONG.KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A_long_KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A.long.KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A-long-KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A.long-KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A-long.KEY")).isEqualTo("a_long_value"); + assertThat(ps.getProperty("A_DOT.KEY")).isEqualTo("a_dot_value"); + assertThat(ps.getProperty("A-DOT.KEY")).isEqualTo("a_dot_value"); + assertThat(ps.getProperty("A_dot.KEY")).isEqualTo("a_dot_value"); + assertThat(ps.getProperty("A-dot.KEY")).isEqualTo("a_dot_value"); + assertThat(ps.getProperty("A_HYPHEN-KEY")).isEqualTo("a_hyphen_value"); + assertThat(ps.getProperty("A.HYPHEN-KEY")).isEqualTo("a_hyphen_value"); + assertThat(ps.getProperty("A_hyphen-KEY")).isEqualTo("a_hyphen_value"); + assertThat(ps.getProperty("A.hyphen-KEY")).isEqualTo("a_hyphen_value"); } @Test @@ -170,8 +170,8 @@ public class SystemEnvironmentPropertySourceTests { } }; - assertThat(ps.containsProperty("A_KEY"), equalTo(true)); - assertThat(ps.getProperty("A_KEY"), equalTo((Object)"a_value")); + assertThat(ps.containsProperty("A_KEY")).isEqualTo(true); + assertThat(ps.getProperty("A_KEY")).isEqualTo((Object)"a_value"); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java index bb9e761468..abf88c8450 100644 --- a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java @@ -28,19 +28,15 @@ import java.nio.file.AccessDeniedException; import java.nio.file.Path; import java.nio.file.Paths; -import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -101,75 +97,75 @@ public class PathResourceTests { public void createFromPath() { Path path = Paths.get(TEST_FILE); PathResource resource = new PathResource(path); - assertThat(resource.getPath(), equalTo(TEST_FILE)); + assertThat(resource.getPath()).isEqualTo(TEST_FILE); } @Test public void createFromString() { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.getPath(), equalTo(TEST_FILE)); + assertThat(resource.getPath()).isEqualTo(TEST_FILE); } @Test public void createFromUri() { File file = new File(TEST_FILE); PathResource resource = new PathResource(file.toURI()); - assertThat(resource.getPath(), equalTo(file.getAbsoluteFile().toString())); + assertThat(resource.getPath()).isEqualTo(file.getAbsoluteFile().toString()); } @Test public void getPathForFile() { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.getPath(), equalTo(TEST_FILE)); + assertThat(resource.getPath()).isEqualTo(TEST_FILE); } @Test public void getPathForDir() { PathResource resource = new PathResource(TEST_DIR); - assertThat(resource.getPath(), equalTo(TEST_DIR)); + assertThat(resource.getPath()).isEqualTo(TEST_DIR); } @Test public void fileExists() { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.exists(), equalTo(true)); + assertThat(resource.exists()).isEqualTo(true); } @Test public void dirExists() { PathResource resource = new PathResource(TEST_DIR); - assertThat(resource.exists(), equalTo(true)); + assertThat(resource.exists()).isEqualTo(true); } @Test public void fileDoesNotExist() { PathResource resource = new PathResource(NON_EXISTING_FILE); - assertThat(resource.exists(), equalTo(false)); + assertThat(resource.exists()).isEqualTo(false); } @Test public void fileIsReadable() { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.isReadable(), equalTo(true)); + assertThat(resource.isReadable()).isEqualTo(true); } @Test public void doesNotExistIsNotReadable() { PathResource resource = new PathResource(NON_EXISTING_FILE); - assertThat(resource.isReadable(), equalTo(false)); + assertThat(resource.isReadable()).isEqualTo(false); } @Test public void directoryIsNotReadable() { PathResource resource = new PathResource(TEST_DIR); - assertThat(resource.isReadable(), equalTo(false)); + assertThat(resource.isReadable()).isEqualTo(false); } @Test public void getInputStream() throws IOException { PathResource resource = new PathResource(TEST_FILE); byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); - assertThat(bytes.length, greaterThan(0)); + assertThat(bytes.length).isGreaterThan(0); } @Test @@ -189,20 +185,20 @@ public class PathResourceTests { @Test public void getUrl() throws IOException { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.getURL().toString(), Matchers.endsWith("core/io/example.properties")); + assertThat(resource.getURL().toString()).endsWith("core/io/example.properties"); } @Test public void getUri() throws IOException { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.getURI().toString(), Matchers.endsWith("core/io/example.properties")); + assertThat(resource.getURI().toString()).endsWith("core/io/example.properties"); } @Test public void getFile() throws IOException { PathResource resource = new PathResource(TEST_FILE); File file = new File(TEST_FILE); - assertThat(resource.getFile().getAbsoluteFile(), equalTo(file.getAbsoluteFile())); + assertThat(resource.getFile().getAbsoluteFile()).isEqualTo(file.getAbsoluteFile()); } @Test @@ -219,65 +215,65 @@ public class PathResourceTests { public void contentLength() throws IOException { PathResource resource = new PathResource(TEST_FILE); File file = new File(TEST_FILE); - assertThat(resource.contentLength(), equalTo(file.length())); + assertThat(resource.contentLength()).isEqualTo(file.length()); } @Test public void contentLengthForDirectory() throws IOException { PathResource resource = new PathResource(TEST_DIR); File file = new File(TEST_DIR); - assertThat(resource.contentLength(), equalTo(file.length())); + assertThat(resource.contentLength()).isEqualTo(file.length()); } @Test public void lastModified() throws IOException { PathResource resource = new PathResource(TEST_FILE); File file = new File(TEST_FILE); - assertThat(resource.lastModified() / 1000, equalTo(file.lastModified() / 1000)); + assertThat(resource.lastModified() / 1000).isEqualTo(file.lastModified() / 1000); } @Test public void createRelativeFromDir() throws IOException { Resource resource = new PathResource(TEST_DIR).createRelative("example.properties"); - assertThat(resource, equalTo((Resource) new PathResource(TEST_FILE))); + assertThat(resource).isEqualTo(new PathResource(TEST_FILE)); } @Test public void createRelativeFromFile() throws IOException { Resource resource = new PathResource(TEST_FILE).createRelative("../example.properties"); - assertThat(resource, equalTo((Resource) new PathResource(TEST_FILE))); + assertThat(resource).isEqualTo(new PathResource(TEST_FILE)); } @Test public void filename() { Resource resource = new PathResource(TEST_FILE); - assertThat(resource.getFilename(), equalTo("example.properties")); + assertThat(resource.getFilename()).isEqualTo("example.properties"); } @Test public void description() { Resource resource = new PathResource(TEST_FILE); - assertThat(resource.getDescription(), containsString("path [")); - assertThat(resource.getDescription(), containsString(TEST_FILE)); + assertThat(resource.getDescription()).contains("path ["); + assertThat(resource.getDescription()).contains(TEST_FILE); } @Test public void fileIsWritable() { PathResource resource = new PathResource(TEST_FILE); - assertThat(resource.isWritable(), equalTo(true)); + assertThat(resource.isWritable()).isEqualTo(true); } @Test public void directoryIsNotWritable() { PathResource resource = new PathResource(TEST_DIR); - assertThat(resource.isWritable(), equalTo(false)); + assertThat(resource.isWritable()).isEqualTo(false); } @Test public void outputStream() throws IOException { PathResource resource = new PathResource(temporaryFolder.newFile("test").toPath()); FileCopyUtils.copy("test".getBytes(StandardCharsets.UTF_8), resource.getOutputStream()); - assertThat(resource.contentLength(), equalTo(4L)); + assertThat(resource.contentLength()).isEqualTo(4L); } @Test @@ -286,7 +282,7 @@ public class PathResourceTests { file.delete(); PathResource resource = new PathResource(file.toPath()); FileCopyUtils.copy("test".getBytes(), resource.getOutputStream()); - assertThat(resource.contentLength(), equalTo(4L)); + assertThat(resource.contentLength()).isEqualTo(4L); } @Test @@ -305,7 +301,7 @@ public class PathResourceTests { ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength()); channel.read(buffer); buffer.rewind(); - assertThat(buffer.limit(), greaterThan(0)); + assertThat(buffer.limit()).isGreaterThan(0); } finally { if (channel != null) { @@ -346,7 +342,7 @@ public class PathResourceTests { channel.close(); } } - assertThat(resource.contentLength(), equalTo(4L)); + assertThat(resource.contentLength()).isEqualTo(4L); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java index e1bde2fd34..2fabfd5b60 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java @@ -32,10 +32,8 @@ import org.junit.Test; import org.springframework.util.FileCopyUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -255,7 +253,7 @@ public class ResourceTests { resource.createRelative("/testing")) .withMessageContaining(name); - assertThat(resource.getFilename(), nullValue()); + assertThat(resource.getFilename()).isNull(); } @Test @@ -270,7 +268,7 @@ public class ResourceTests { return ""; } }; - assertThat(resource.contentLength(), is(3L)); + assertThat(resource.contentLength()).isEqualTo(3L); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java index 8e7fa320d3..4248fb9782 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java @@ -24,8 +24,7 @@ import org.springframework.core.env.PropertySource; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ClassPathResource; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -49,49 +48,49 @@ public class ResourcePropertySourceTests { public void withLocationAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(PROPERTIES_LOCATION); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION)); + assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void xmlWithLocationAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(XML_PROPERTIES_LOCATION); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is(XML_PROPERTIES_RESOURCE_DESCRIPTION)); + assertThat(ps.getName()).isEqualTo(XML_PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void withLocationAndExplicitName() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is("ps1")); + assertThat(ps.getName()).isEqualTo("ps1"); } @Test public void withLocationAndExplicitNameAndExplicitClassLoader() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION, getClass().getClassLoader()); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is("ps1")); + assertThat(ps.getName()).isEqualTo("ps1"); } @Test public void withLocationAndGeneratedNameAndExplicitClassLoader() throws IOException { PropertySource ps = new ResourcePropertySource(PROPERTIES_LOCATION, getClass().getClassLoader()); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION)); + assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void withResourceAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(new ClassPathResource(PROPERTIES_PATH)); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION)); + assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void withResourceAndExplicitName() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", new ClassPathResource(PROPERTIES_PATH)); assertEquals("bar", ps.getProperty("foo")); - assertThat(ps.getName(), is("ps1")); + assertThat(ps.getName()).isEqualTo("ps1"); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java b/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java index 18b7b326ec..7b45335713 100644 --- a/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java +++ b/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java @@ -22,10 +22,9 @@ import org.junit.Test; import org.springframework.util.ConcurrencyThrottleSupport; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -59,7 +58,7 @@ public class SimpleAsyncTaskExecutorTests { SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(customPrefix); ThreadNameHarvester task = new ThreadNameHarvester(monitor); executeAndWait(executor, task, monitor); - assertThat(task.getThreadName(), startsWith(customPrefix)); + assertThat(task.getThreadName()).startsWith(customPrefix); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/type/AbstractClassMetadataMemberClassTests.java b/spring-core/src/test/java/org/springframework/core/type/AbstractClassMetadataMemberClassTests.java index ebed1cbdb6..24fd1b5186 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AbstractClassMetadataMemberClassTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AbstractClassMetadataMemberClassTests.java @@ -18,8 +18,8 @@ package org.springframework.core.type; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Abstract base class for testing implementations of @@ -36,7 +36,7 @@ public abstract class AbstractClassMetadataMemberClassTests { public void withNoMemberClasses() { ClassMetadata metadata = getClassMetadataFor(L0_a.class); String[] nestedClasses = metadata.getMemberClassNames(); - assertThat(nestedClasses, equalTo(new String[]{})); + assertThat(nestedClasses).isEqualTo(new String[]{}); } public static class L0_a { @@ -47,7 +47,7 @@ public abstract class AbstractClassMetadataMemberClassTests { public void withPublicMemberClasses() { ClassMetadata metadata = getClassMetadataFor(L0_b.class); String[] nestedClasses = metadata.getMemberClassNames(); - assertThat(nestedClasses, equalTo(new String[]{L0_b.L1.class.getName()})); + assertThat(nestedClasses).isEqualTo(new String[]{L0_b.L1.class.getName()}); } public static class L0_b { @@ -59,7 +59,7 @@ public abstract class AbstractClassMetadataMemberClassTests { public void withNonPublicMemberClasses() { ClassMetadata metadata = getClassMetadataFor(L0_c.class); String[] nestedClasses = metadata.getMemberClassNames(); - assertThat(nestedClasses, equalTo(new String[]{L0_c.L1.class.getName()})); + assertThat(nestedClasses).isEqualTo(new String[]{L0_c.L1.class.getName()}); } public static class L0_c { @@ -71,7 +71,7 @@ public abstract class AbstractClassMetadataMemberClassTests { public void againstMemberClass() { ClassMetadata metadata = getClassMetadataFor(L0_b.L1.class); String[] nestedClasses = metadata.getMemberClassNames(); - assertThat(nestedClasses, equalTo(new String[]{})); + assertThat(nestedClasses).isEqualTo(new String[]{}); } } 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 f402345915..f360bd9426 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 @@ -38,11 +38,7 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.stereotype.Component; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -90,25 +86,25 @@ public class AnnotationMetadataTests { } private void doTestSubClassAnnotationInfo(AnnotationMetadata metadata) { - assertThat(metadata.getClassName(), is(AnnotatedComponentSubClass.class.getName())); - assertThat(metadata.isInterface(), is(false)); - assertThat(metadata.isAnnotation(), is(false)); - assertThat(metadata.isAbstract(), is(false)); - assertThat(metadata.isConcrete(), is(true)); - assertThat(metadata.hasSuperClass(), is(true)); - assertThat(metadata.getSuperClassName(), is(AnnotatedComponent.class.getName())); - assertThat(metadata.getInterfaceNames().length, is(0)); - assertThat(metadata.isAnnotated(Component.class.getName()), is(false)); - assertThat(metadata.isAnnotated(Scope.class.getName()), is(false)); - assertThat(metadata.isAnnotated(SpecialAttr.class.getName()), is(false)); - assertThat(metadata.hasAnnotation(Component.class.getName()), is(false)); - assertThat(metadata.hasAnnotation(Scope.class.getName()), is(false)); - assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(false)); - assertThat(metadata.getAnnotationTypes().size(), is(0)); - assertThat(metadata.getAnnotationAttributes(Component.class.getName()), nullValue()); - assertThat(metadata.getAnnotatedMethods(DirectAnnotation.class.getName()).size(), equalTo(0)); - assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName()), equalTo(false)); - assertThat(metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()), nullValue()); + assertThat(metadata.getClassName()).isEqualTo(AnnotatedComponentSubClass.class.getName()); + assertThat(metadata.isInterface()).isFalse(); + assertThat(metadata.isAnnotation()).isFalse(); + assertThat(metadata.isAbstract()).isFalse(); + assertThat(metadata.isConcrete()).isTrue(); + assertThat(metadata.hasSuperClass()).isTrue(); + assertThat(metadata.getSuperClassName()).isEqualTo(AnnotatedComponent.class.getName()); + assertThat(metadata.getInterfaceNames().length).isEqualTo(0); + assertThat(metadata.isAnnotated(Component.class.getName())).isFalse(); + assertThat(metadata.isAnnotated(Scope.class.getName())).isFalse(); + assertThat(metadata.isAnnotated(SpecialAttr.class.getName())).isFalse(); + assertThat(metadata.hasAnnotation(Component.class.getName())).isFalse(); + assertThat(metadata.hasAnnotation(Scope.class.getName())).isFalse(); + assertThat(metadata.hasAnnotation(SpecialAttr.class.getName())).isFalse(); + assertThat(metadata.getAnnotationTypes()).hasSize(0); + assertThat(metadata.getAnnotationAttributes(Component.class.getName())).isNull(); + assertThat(metadata.getAnnotatedMethods(DirectAnnotation.class.getName()).size()).isEqualTo(0); + assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())).isEqualTo(false); + assertThat(metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName())).isNull(); } @Test @@ -126,17 +122,17 @@ public class AnnotationMetadataTests { } private void doTestMetadataForInterfaceClass(AnnotationMetadata metadata) { - assertThat(metadata.getClassName(), is(AnnotationMetadata.class.getName())); - assertThat(metadata.isInterface(), is(true)); - assertThat(metadata.isAnnotation(), is(false)); - assertThat(metadata.isAbstract(), is(true)); - assertThat(metadata.isConcrete(), is(false)); - assertThat(metadata.hasSuperClass(), is(false)); - assertThat(metadata.getSuperClassName(), nullValue()); - assertThat(metadata.getInterfaceNames().length, is(2)); - assertThat(metadata.getInterfaceNames()[0], is(ClassMetadata.class.getName())); - assertThat(metadata.getInterfaceNames()[1], is(AnnotatedTypeMetadata.class.getName())); - assertThat(metadata.getAnnotationTypes().size(), is(0)); + assertThat(metadata.getClassName()).isEqualTo(AnnotationMetadata.class.getName()); + assertThat(metadata.isInterface()).isTrue(); + assertThat(metadata.isAnnotation()).isFalse(); + assertThat(metadata.isAbstract()).isTrue(); + assertThat(metadata.isConcrete()).isFalse(); + assertThat(metadata.hasSuperClass()).isFalse(); + assertThat(metadata.getSuperClassName()).isNull(); + assertThat(metadata.getInterfaceNames().length).isEqualTo(2); + assertThat(metadata.getInterfaceNames()[0]).isEqualTo(ClassMetadata.class.getName()); + assertThat(metadata.getInterfaceNames()[1]).isEqualTo(AnnotatedTypeMetadata.class.getName()); + assertThat(metadata.getAnnotationTypes()).hasSize(0); } @Test @@ -154,22 +150,22 @@ public class AnnotationMetadataTests { } private void doTestMetadataForAnnotationClass(AnnotationMetadata metadata) { - assertThat(metadata.getClassName(), is(Component.class.getName())); - assertThat(metadata.isInterface(), is(true)); - assertThat(metadata.isAnnotation(), is(true)); - assertThat(metadata.isAbstract(), is(true)); - assertThat(metadata.isConcrete(), is(false)); - assertThat(metadata.hasSuperClass(), is(false)); - assertThat(metadata.getSuperClassName(), nullValue()); - assertThat(metadata.getInterfaceNames().length, is(1)); - assertThat(metadata.getInterfaceNames()[0], is(Annotation.class.getName())); - assertThat(metadata.isAnnotated(Documented.class.getName()), is(false)); - assertThat(metadata.isAnnotated(Scope.class.getName()), is(false)); - assertThat(metadata.isAnnotated(SpecialAttr.class.getName()), is(false)); - assertThat(metadata.hasAnnotation(Documented.class.getName()), is(false)); - assertThat(metadata.hasAnnotation(Scope.class.getName()), is(false)); - assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(false)); - assertThat(metadata.getAnnotationTypes().size(), is(1)); + assertThat(metadata.getClassName()).isEqualTo(Component.class.getName()); + assertThat(metadata.isInterface()).isTrue(); + assertThat(metadata.isAnnotation()).isTrue(); + assertThat(metadata.isAbstract()).isTrue(); + assertThat(metadata.isConcrete()).isFalse(); + assertThat(metadata.hasSuperClass()).isFalse(); + assertThat(metadata.getSuperClassName()).isNull(); + assertThat(metadata.getInterfaceNames().length).isEqualTo(1); + assertThat(metadata.getInterfaceNames()[0]).isEqualTo(Annotation.class.getName()); + assertThat(metadata.isAnnotated(Documented.class.getName())).isFalse(); + assertThat(metadata.isAnnotated(Scope.class.getName())).isFalse(); + assertThat(metadata.isAnnotated(SpecialAttr.class.getName())).isFalse(); + assertThat(metadata.hasAnnotation(Documented.class.getName())).isFalse(); + assertThat(metadata.hasAnnotation(Scope.class.getName())).isFalse(); + assertThat(metadata.hasAnnotation(SpecialAttr.class.getName())).isFalse(); + assertThat(metadata.getAnnotationTypes()).hasSize(1); } /** @@ -185,7 +181,7 @@ public class AnnotationMetadataTests { AnnotationMetadata metadata = new StandardAnnotationMetadata(AnnotatedComponent.class); AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName()); Annotation[] nestedAnnoArray = (Annotation[]) specialAttrs.get("nestedAnnoArray"); - assertThat(nestedAnnoArray[0], instanceOf(NestedAnno.class)); + assertThat(nestedAnnoArray[0]).isInstanceOf(NestedAnno.class); } @Test @@ -206,13 +202,9 @@ public class AnnotationMetadataTests { private void assertMetaAnnotationOverrides(AnnotationMetadata metadata) { AnnotationAttributes attributes = (AnnotationAttributes) metadata.getAnnotationAttributes( TestComponentScan.class.getName(), false); - String[] basePackages = attributes.getStringArray("basePackages"); - assertThat("length of basePackages[]", basePackages.length, is(1)); - assertThat("basePackages[0]", basePackages[0], is("org.example.componentscan")); - String[] value = attributes.getStringArray("value"); - assertThat("length of value[]", value.length, is(0)); - Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); - assertThat("length of basePackageClasses[]", basePackageClasses.length, is(0)); + assertThat(attributes.getStringArray("basePackages")).containsExactly("org.example.componentscan"); + assertThat(attributes.getStringArray("value")).isEmpty(); + assertThat(attributes.getClassArray("basePackageClasses")).isEmpty(); } @Test // SPR-11649 @@ -262,104 +254,104 @@ public class AnnotationMetadataTests { AnnotationAttributes attributes1 = (AnnotationAttributes) metadata.getAnnotationAttributes( NamedAnnotation1.class.getName(), false); String name1 = attributes1.getString("name"); - assertThat("name of NamedAnnotation1", name1, is("name 1")); + assertThat(name1).as("name of NamedAnnotation1").isEqualTo("name 1"); AnnotationAttributes attributes2 = (AnnotationAttributes) metadata.getAnnotationAttributes( NamedAnnotation2.class.getName(), false); String name2 = attributes2.getString("name"); - assertThat("name of NamedAnnotation2", name2, is("name 2")); + assertThat(name2).as("name of NamedAnnotation2").isEqualTo("name 2"); AnnotationAttributes attributes3 = (AnnotationAttributes) metadata.getAnnotationAttributes( NamedAnnotation3.class.getName(), false); String name3 = attributes3.getString("name"); - assertThat("name of NamedAnnotation3", name3, is("name 3")); + assertThat(name3).as("name of NamedAnnotation3").isEqualTo("name 3"); } private void doTestAnnotationInfo(AnnotationMetadata metadata) { - assertThat(metadata.getClassName(), is(AnnotatedComponent.class.getName())); - assertThat(metadata.isInterface(), is(false)); - assertThat(metadata.isAnnotation(), is(false)); - assertThat(metadata.isAbstract(), is(false)); - assertThat(metadata.isConcrete(), is(true)); - assertThat(metadata.hasSuperClass(), is(true)); - assertThat(metadata.getSuperClassName(), is(Object.class.getName())); - assertThat(metadata.getInterfaceNames().length, is(1)); - assertThat(metadata.getInterfaceNames()[0], is(Serializable.class.getName())); + assertThat(metadata.getClassName()).isEqualTo(AnnotatedComponent.class.getName()); + assertThat(metadata.isInterface()).isFalse(); + assertThat(metadata.isAnnotation()).isFalse(); + assertThat(metadata.isAbstract()).isFalse(); + assertThat(metadata.isConcrete()).isTrue(); + assertThat(metadata.hasSuperClass()).isTrue(); + assertThat(metadata.getSuperClassName()).isEqualTo(Object.class.getName()); + assertThat(metadata.getInterfaceNames().length).isEqualTo(1); + assertThat(metadata.getInterfaceNames()[0]).isEqualTo(Serializable.class.getName()); - assertThat(metadata.hasAnnotation(Component.class.getName()), is(true)); - assertThat(metadata.hasAnnotation(Scope.class.getName()), is(true)); - assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(true)); - assertThat(metadata.getAnnotationTypes().size(), is(6)); - assertThat(metadata.getAnnotationTypes().contains(Component.class.getName()), is(true)); - assertThat(metadata.getAnnotationTypes().contains(Scope.class.getName()), is(true)); - assertThat(metadata.getAnnotationTypes().contains(SpecialAttr.class.getName()), is(true)); + assertThat(metadata.hasAnnotation(Component.class.getName())).isTrue(); + assertThat(metadata.hasAnnotation(Scope.class.getName())).isTrue(); + assertThat(metadata.hasAnnotation(SpecialAttr.class.getName())).isTrue(); + assertThat(metadata.getAnnotationTypes()).hasSize(6); + assertThat(metadata.getAnnotationTypes().contains(Component.class.getName())).isTrue(); + assertThat(metadata.getAnnotationTypes().contains(Scope.class.getName())).isTrue(); + assertThat(metadata.getAnnotationTypes().contains(SpecialAttr.class.getName())).isTrue(); AnnotationAttributes compAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(Component.class.getName()); - assertThat(compAttrs.size(), is(1)); - assertThat(compAttrs.getString("value"), is("myName")); + assertThat(compAttrs).hasSize(1); + assertThat(compAttrs.getString("value")).isEqualTo("myName"); AnnotationAttributes scopeAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(Scope.class.getName()); - assertThat(scopeAttrs.size(), is(1)); - assertThat(scopeAttrs.getString("value"), is("myScope")); + assertThat(scopeAttrs).hasSize(1); + assertThat(scopeAttrs.getString("value")).isEqualTo("myScope"); Set methods = metadata.getAnnotatedMethods(DirectAnnotation.class.getName()); MethodMetadata method = methods.iterator().next(); assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("myValue")); List allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); - assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet(Arrays.asList("direct", "meta"))))); + assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", "meta"))); allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional"); - assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet(Arrays.asList("direct"))))); + assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct"))); assertTrue(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())); { // perform tests with classValuesAsString = false (the default) AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName()); - assertThat(specialAttrs.size(), is(6)); + assertThat(specialAttrs).hasSize(6); assertTrue(String.class.isAssignableFrom(specialAttrs.getClass("clazz"))); assertTrue(specialAttrs.getEnum("state").equals(Thread.State.NEW)); AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno"); - assertThat("na", is(nestedAnno.getString("value"))); + assertThat("na").isEqualTo(nestedAnno.getString("value")); assertTrue(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1)); assertArrayEquals(new Class[] {String.class}, (Class[]) nestedAnno.get("classArray")); AnnotationAttributes[] nestedAnnoArray = specialAttrs.getAnnotationArray("nestedAnnoArray"); - assertThat(nestedAnnoArray.length, is(2)); - assertThat(nestedAnnoArray[0].getString("value"), is("default")); + assertThat(nestedAnnoArray.length).isEqualTo(2); + assertThat(nestedAnnoArray[0].getString("value")).isEqualTo("default"); assertTrue(nestedAnnoArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)); assertArrayEquals(new Class[] {Void.class}, (Class[]) nestedAnnoArray[0].get("classArray")); - assertThat(nestedAnnoArray[1].getString("value"), is("na1")); + assertThat(nestedAnnoArray[1].getString("value")).isEqualTo("na1"); assertTrue(nestedAnnoArray[1].getEnum("anEnum").equals(SomeEnum.LABEL2)); assertArrayEquals(new Class[] {Number.class}, (Class[]) nestedAnnoArray[1].get("classArray")); assertArrayEquals(new Class[] {Number.class}, nestedAnnoArray[1].getClassArray("classArray")); AnnotationAttributes optional = specialAttrs.getAnnotation("optional"); - assertThat(optional.getString("value"), is("optional")); + assertThat(optional.getString("value")).isEqualTo("optional"); assertTrue(optional.getEnum("anEnum").equals(SomeEnum.DEFAULT)); assertArrayEquals(new Class[] {Void.class}, (Class[]) optional.get("classArray")); assertArrayEquals(new Class[] {Void.class}, optional.getClassArray("classArray")); AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray"); - assertThat(optionalArray.length, is(1)); - assertThat(optionalArray[0].getString("value"), is("optional")); + assertThat(optionalArray.length).isEqualTo(1); + assertThat(optionalArray[0].getString("value")).isEqualTo("optional"); assertTrue(optionalArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)); assertArrayEquals(new Class[] {Void.class}, (Class[]) optionalArray[0].get("classArray")); assertArrayEquals(new Class[] {Void.class}, optionalArray[0].getClassArray("classArray")); assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); - assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet(Arrays.asList("direct", "meta"))))); + assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", "meta"))); allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional"); - assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet(Arrays.asList("direct", ""))))); + assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", ""))); assertEquals("", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additional")); assertEquals(0, ((String[]) metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additionalArray")).length); } { // perform tests with classValuesAsString = true AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes( SpecialAttr.class.getName(), true); - assertThat(specialAttrs.size(), is(6)); - assertThat(specialAttrs.get("clazz"), is((Object) String.class.getName())); - assertThat(specialAttrs.getString("clazz"), is(String.class.getName())); + assertThat(specialAttrs).hasSize(6); + assertThat(specialAttrs.get("clazz")).isEqualTo(String.class.getName()); + assertThat(specialAttrs.getString("clazz")).isEqualTo(String.class.getName()); AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno"); assertArrayEquals(new String[] { String.class.getName() }, nestedAnno.getStringArray("classArray")); @@ -381,15 +373,15 @@ public class AnnotationMetadataTests { assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); - assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet(Arrays.asList("direct", "meta"))))); + assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", "meta"))); } } private void doTestMethodAnnotationInfo(AnnotationMetadata classMetadata) { Set methods = classMetadata.getAnnotatedMethods(TestAutowired.class.getName()); - assertThat(methods.size(), is(1)); + assertThat(methods).hasSize(1); for (MethodMetadata methodMetadata : methods) { - assertThat(methodMetadata.isAnnotated(TestAutowired.class.getName()), is(true)); + assertThat(methodMetadata.isAnnotated(TestAutowired.class.getName())).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTests.java b/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTests.java index 2cda73b752..88092c515c 100644 --- a/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTests.java @@ -28,8 +28,8 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for checking the behaviour of {@link CachingMetadataReaderFactory} under @@ -51,7 +51,7 @@ public class CachingMetadataReaderLeakTests { // the biggest public class in the JDK (>60k) URL url = getClass().getResource("/java/awt/Component.class"); - assertThat(url, notNullValue()); + assertThat(url).isNotNull(); // look at a LOT of items for (int i = 0; i < ITEMS_TO_LOAD; i++) { @@ -69,7 +69,7 @@ public class CachingMetadataReaderLeakTests { }; MetadataReader reader = mrf.getMetadataReader(resource); - assertThat(reader, notNullValue()); + assertThat(reader).isNotNull(); } // useful for profiling to take snapshots diff --git a/spring-core/src/test/java/org/springframework/tests/AssumeTests.java b/spring-core/src/test/java/org/springframework/tests/AssumeTests.java index 49085642a1..ea9ca66138 100644 --- a/spring-core/src/test/java/org/springframework/tests/AssumeTests.java +++ b/spring-core/src/test/java/org/springframework/tests/AssumeTests.java @@ -24,10 +24,7 @@ import org.junit.Before; import org.junit.Test; import static java.util.stream.Collectors.joining; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.springframework.tests.Assume.TEST_GROUPS_SYSTEM_PROPERTY; import static org.springframework.tests.TestGroup.CI; @@ -108,13 +105,13 @@ public class AssumeTests { fail("assumption should have failed"); } catch (IllegalStateException ex) { - assertThat(ex.getMessage(), - startsWith("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY + "' system property: ")); + assertThat(ex.getMessage()). + startsWith("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY + "' system property: "); - assertThat(ex.getCause(), instanceOf(IllegalArgumentException.class)); - assertThat(ex.getCause().getMessage(), - equalTo("Unable to find test group 'bogus' when parsing testGroups value: '" + testGroups - + "'. Available groups include: [LONG_RUNNING,PERFORMANCE,CI]")); + assertThat(ex.getCause()).isInstanceOf(IllegalArgumentException.class); + assertThat(ex.getCause().getMessage()). + isEqualTo("Unable to find test group 'bogus' when parsing testGroups value: '" + testGroups + + "'. Available groups include: [LONG_RUNNING,PERFORMANCE,CI]"); } } 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 288899c7c8..7c8d27b03f 100644 --- a/spring-core/src/test/java/org/springframework/tests/MockitoUtils.java +++ b/spring-core/src/test/java/org/springframework/tests/MockitoUtils.java @@ -23,9 +23,10 @@ import org.mockito.internal.stubbing.InvocationContainerImpl; import org.mockito.internal.util.MockUtil; import org.mockito.invocation.Invocation; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; + + + /** * General test utilities for use with {@link Mockito}. @@ -52,7 +53,7 @@ public abstract class MockitoUtils { private static void verifySameInvocations(List expectedInvocations, List actualInvocations, InvocationArgumentsAdapter... argumentAdapters) { - assertThat(expectedInvocations.size(), is(equalTo(actualInvocations.size()))); + assertThat(expectedInvocations.size()).isEqualTo(actualInvocations.size()); for (int i = 0; i < expectedInvocations.size(); i++) { verifySameInvocation(expectedInvocations.get(i), actualInvocations.get(i), argumentAdapters); } @@ -61,10 +62,10 @@ public abstract class MockitoUtils { private static void verifySameInvocation(Invocation expectedInvocation, Invocation actualInvocation, InvocationArgumentsAdapter... argumentAdapters) { - assertThat(expectedInvocation.getMethod(), is(equalTo(actualInvocation.getMethod()))); + assertThat(expectedInvocation.getMethod()).isEqualTo(actualInvocation.getMethod()); Object[] expectedArguments = getInvocationArguments(expectedInvocation, argumentAdapters); Object[] actualArguments = getInvocationArguments(actualInvocation, argumentAdapters); - assertThat(expectedArguments, is(equalTo(actualArguments))); + assertThat(expectedArguments).isEqualTo(actualArguments); } private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) { diff --git a/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java b/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java index fdc782429f..df86e0c3e2 100644 --- a/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java +++ b/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java @@ -22,9 +22,9 @@ import java.util.Set; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; + /** * Tests for {@link TestGroup}. @@ -36,29 +36,29 @@ public class TestGroupTests { @Test public void parseNull() { - assertThat(TestGroup.parse(null), equalTo(Collections.emptySet())); + assertThat(TestGroup.parse(null)).isEqualTo(Collections.emptySet()); } @Test public void parseEmptyString() { - assertThat(TestGroup.parse(""), equalTo(Collections.emptySet())); + assertThat(TestGroup.parse("")).isEqualTo(Collections.emptySet()); } @Test public void parseBlankString() { - assertThat(TestGroup.parse(" "), equalTo(Collections.emptySet())); + assertThat(TestGroup.parse(" ")).isEqualTo(Collections.emptySet()); } @Test public void parseWithSpaces() { - assertThat(TestGroup.parse(" PERFORMANCE, PERFORMANCE "), - equalTo(EnumSet.of(TestGroup.PERFORMANCE))); + assertThat(TestGroup.parse(" PERFORMANCE, PERFORMANCE ")).containsOnly( + TestGroup.PERFORMANCE); } @Test public void parseInMixedCase() { - assertThat(TestGroup.parse("performance, PERFormaNCE"), - equalTo(EnumSet.of(TestGroup.PERFORMANCE))); + assertThat(TestGroup.parse("performance, PERFormaNCE")).containsOnly( + TestGroup.PERFORMANCE); } @Test @@ -72,14 +72,14 @@ public class TestGroupTests { @Test public void parseAll() { - assertThat(TestGroup.parse("all"), equalTo(EnumSet.allOf(TestGroup.class))); + assertThat(TestGroup.parse("all")).isEqualTo(EnumSet.allOf(TestGroup.class)); } @Test public void parseAllExceptPerformance() { Set expected = EnumSet.allOf(TestGroup.class); expected.remove(TestGroup.PERFORMANCE); - assertThat(TestGroup.parse("all-performance"), equalTo(expected)); + assertThat(TestGroup.parse("all-performance")).isEqualTo(expected); } @Test diff --git a/spring-core/src/test/java/org/springframework/tests/XmlContent.java b/spring-core/src/test/java/org/springframework/tests/XmlContent.java new file mode 100644 index 0000000000..df4342a68e --- /dev/null +++ b/spring-core/src/test/java/org/springframework/tests/XmlContent.java @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2019 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.tests; + +import java.io.StringWriter; + +import org.assertj.core.api.AssertProvider; +import org.xmlunit.assertj.XmlAssert; + +/** + * {@link AssertProvider} to allow XML content assertions. Ultimately delegates + * to {@link XmlAssert}. + * + * @author Phillip Webb + */ +public class XmlContent implements AssertProvider { + + private Object source; + + private XmlContent(Object source) { + this.source = source; + } + + @Override + public XmlContentAssert assertThat() { + return new XmlContentAssert(this.source); + } + + public static XmlContent from(Object source) { + return of(source); + } + + public static XmlContent of(Object source) { + if (source instanceof StringWriter) { + return of(source.toString()); + } + return new XmlContent(source); + } + +} diff --git a/spring-core/src/test/java/org/springframework/tests/XmlContentAssert.java b/spring-core/src/test/java/org/springframework/tests/XmlContentAssert.java new file mode 100644 index 0000000000..b598f5f363 --- /dev/null +++ b/spring-core/src/test/java/org/springframework/tests/XmlContentAssert.java @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2019 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.tests; + +import org.assertj.core.api.AbstractAssert; +import org.w3c.dom.Node; +import org.xmlunit.assertj.XmlAssert; +import org.xmlunit.diff.DifferenceEvaluator; +import org.xmlunit.diff.NodeMatcher; +import org.xmlunit.util.Predicate; + +/** + * Assertions exposed by {@link XmlContent}. + * + * @author Phillip Webb + */ +public class XmlContentAssert extends AbstractAssert { + + XmlContentAssert(Object actual) { + super(actual, XmlContentAssert.class); + } + + public XmlContentAssert isSimilarTo(Object control) { + XmlAssert.assertThat(actual).and(control).areSimilar(); + return this; + } + + public XmlContentAssert isSimilarTo(Object control, Predicate nodeFilter) { + XmlAssert.assertThat(actual).and(control).withNodeFilter(nodeFilter).areSimilar(); + return this; + } + + public XmlContentAssert isSimilarTo(String control, + DifferenceEvaluator differenceEvaluator) { + XmlAssert.assertThat(actual).and(control).withDifferenceEvaluator( + differenceEvaluator).areSimilar(); + return this; + } + + public XmlContentAssert isSimilarToIgnoringWhitespace(Object control) { + XmlAssert.assertThat(actual).and(control).ignoreWhitespace().areSimilar(); + return this; + } + + + public XmlContentAssert isSimilarToIgnoringWhitespace(String control, NodeMatcher nodeMatcher) { + XmlAssert.assertThat(actual).and(control).ignoreWhitespace().withNodeMatcher(nodeMatcher).areSimilar(); + return this; + } + +} diff --git a/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java b/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java index 0eaa933f2e..76e4e9f699 100644 --- a/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java +++ b/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java @@ -39,12 +39,8 @@ import org.springframework.util.ConcurrentReferenceHashMap.Restructure; import org.springframework.util.comparator.ComparableComparator; import org.springframework.util.comparator.NullSafeComparator; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertFalse; /** @@ -63,43 +59,43 @@ public class ConcurrentReferenceHashMapTests { @Test public void shouldCreateWithDefaults() { ConcurrentReferenceHashMap map = new ConcurrentReferenceHashMap<>(); - assertThat(map.getSegmentsSize(), is(16)); - assertThat(map.getSegment(0).getSize(), is(1)); - assertThat(map.getLoadFactor(), is(0.75f)); + assertThat(map.getSegmentsSize()).isEqualTo(16); + assertThat(map.getSegment(0).getSize()).isEqualTo(1); + assertThat(map.getLoadFactor()).isEqualTo(0.75f); } @Test public void shouldCreateWithInitialCapacity() { ConcurrentReferenceHashMap map = new ConcurrentReferenceHashMap<>(32); - assertThat(map.getSegmentsSize(), is(16)); - assertThat(map.getSegment(0).getSize(), is(2)); - assertThat(map.getLoadFactor(), is(0.75f)); + assertThat(map.getSegmentsSize()).isEqualTo(16); + assertThat(map.getSegment(0).getSize()).isEqualTo(2); + assertThat(map.getLoadFactor()).isEqualTo(0.75f); } @Test public void shouldCreateWithInitialCapacityAndLoadFactor() { ConcurrentReferenceHashMap map = new ConcurrentReferenceHashMap<>(32, 0.5f); - assertThat(map.getSegmentsSize(), is(16)); - assertThat(map.getSegment(0).getSize(), is(2)); - assertThat(map.getLoadFactor(), is(0.5f)); + assertThat(map.getSegmentsSize()).isEqualTo(16); + assertThat(map.getSegment(0).getSize()).isEqualTo(2); + assertThat(map.getLoadFactor()).isEqualTo(0.5f); } @Test public void shouldCreateWithInitialCapacityAndConcurrentLevel() { ConcurrentReferenceHashMap map = new ConcurrentReferenceHashMap<>(16, 2); - assertThat(map.getSegmentsSize(), is(2)); - assertThat(map.getSegment(0).getSize(), is(8)); - assertThat(map.getLoadFactor(), is(0.75f)); + assertThat(map.getSegmentsSize()).isEqualTo(2); + assertThat(map.getSegment(0).getSize()).isEqualTo(8); + assertThat(map.getLoadFactor()).isEqualTo(0.75f); } @Test public void shouldCreateFullyCustom() { ConcurrentReferenceHashMap map = new ConcurrentReferenceHashMap<>(5, 0.5f, 3); // concurrencyLevel of 3 ends up as 4 (nearest power of 2) - assertThat(map.getSegmentsSize(), is(4)); + assertThat(map.getSegmentsSize()).isEqualTo(4); // initialCapacity is 5/4 (rounded up, to nearest power of 2) - assertThat(map.getSegment(0).getSize(), is(2)); - assertThat(map.getLoadFactor(), is(0.5f)); + assertThat(map.getSegment(0).getSize()).isEqualTo(2); + assertThat(map.getLoadFactor()).isEqualTo(0.5f); } @Test @@ -129,55 +125,55 @@ public class ConcurrentReferenceHashMapTests { @Test public void shouldPutAndGet() { // NOTE we are using mock references so we don't need to worry about GC - assertThat(this.map.size(), is(0)); + assertThat(this.map).hasSize(0); this.map.put(123, "123"); - assertThat(this.map.get(123), is("123")); - assertThat(this.map.size(), is(1)); + assertThat(this.map.get(123)).isEqualTo("123"); + assertThat(this.map).hasSize(1); this.map.put(123, "123b"); - assertThat(this.map.size(), is(1)); + assertThat(this.map).hasSize(1); this.map.put(123, null); - assertThat(this.map.size(), is(1)); + assertThat(this.map).hasSize(1); } @Test public void shouldReplaceOnDoublePut() { this.map.put(123, "321"); this.map.put(123, "123"); - assertThat(this.map.get(123), is("123")); + assertThat(this.map.get(123)).isEqualTo("123"); } @Test public void shouldPutNullKey() { - assertThat(this.map.get(null), is(nullValue())); - assertThat(this.map.getOrDefault(null, "456"), is("456")); + assertThat(this.map.get(null)).isNull(); + assertThat(this.map.getOrDefault(null, "456")).isEqualTo("456"); this.map.put(null, "123"); - assertThat(this.map.get(null), is("123")); - assertThat(this.map.getOrDefault(null, "456"), is("123")); + assertThat(this.map.get(null)).isEqualTo("123"); + assertThat(this.map.getOrDefault(null, "456")).isEqualTo("123"); } @Test public void shouldPutNullValue() { - assertThat(this.map.get(123), is(nullValue())); - assertThat(this.map.getOrDefault(123, "456"), is("456")); + assertThat(this.map.get(123)).isNull(); + assertThat(this.map.getOrDefault(123, "456")).isEqualTo("456"); this.map.put(123, "321"); - assertThat(this.map.get(123), is("321")); - assertThat(this.map.getOrDefault(123, "456"), is("321")); + assertThat(this.map.get(123)).isEqualTo("321"); + assertThat(this.map.getOrDefault(123, "456")).isEqualTo("321"); this.map.put(123, null); - assertThat(this.map.get(123), is(nullValue())); - assertThat(this.map.getOrDefault(123, "456"), is(nullValue())); + assertThat(this.map.get(123)).isNull(); + assertThat(this.map.getOrDefault(123, "456")).isNull(); } @Test public void shouldGetWithNoItems() { - assertThat(this.map.get(123), is(nullValue())); + assertThat(this.map.get(123)).isNull(); } @Test public void shouldApplySupplementalHash() { Integer key = 123; this.map.put(key, "123"); - assertThat(this.map.getSupplementalHash(), is(not(key.hashCode()))); - assertThat(this.map.getSupplementalHash() >> 30 & 0xFF, is(not(0))); + assertThat(this.map.getSupplementalHash()).isNotEqualTo(key.hashCode()); + assertThat(this.map.getSupplementalHash() >> 30 & 0xFF).isNotEqualTo(0); } @Test @@ -187,41 +183,41 @@ public class ConcurrentReferenceHashMapTests { this.map.put(1, "1"); this.map.put(2, "2"); this.map.put(3, "3"); - assertThat(this.map.getSegment(0).getSize(), is(1)); - assertThat(this.map.get(1), is("1")); - assertThat(this.map.get(2), is("2")); - assertThat(this.map.get(3), is("3")); - assertThat(this.map.get(4), is(nullValue())); + assertThat(this.map.getSegment(0).getSize()).isEqualTo(1); + assertThat(this.map.get(1)).isEqualTo("1"); + assertThat(this.map.get(2)).isEqualTo("2"); + assertThat(this.map.get(3)).isEqualTo("3"); + assertThat(this.map.get(4)).isNull(); } @Test public void shouldResize() { this.map = new TestWeakConcurrentCache<>(1, 0.75f, 1); this.map.put(1, "1"); - assertThat(this.map.getSegment(0).getSize(), is(1)); - assertThat(this.map.get(1), is("1")); + assertThat(this.map.getSegment(0).getSize()).isEqualTo(1); + assertThat(this.map.get(1)).isEqualTo("1"); this.map.put(2, "2"); - assertThat(this.map.getSegment(0).getSize(), is(2)); - assertThat(this.map.get(1), is("1")); - assertThat(this.map.get(2), is("2")); + assertThat(this.map.getSegment(0).getSize()).isEqualTo(2); + assertThat(this.map.get(1)).isEqualTo("1"); + assertThat(this.map.get(2)).isEqualTo("2"); this.map.put(3, "3"); - assertThat(this.map.getSegment(0).getSize(), is(4)); - assertThat(this.map.get(1), is("1")); - assertThat(this.map.get(2), is("2")); - assertThat(this.map.get(3), is("3")); + assertThat(this.map.getSegment(0).getSize()).isEqualTo(4); + assertThat(this.map.get(1)).isEqualTo("1"); + assertThat(this.map.get(2)).isEqualTo("2"); + assertThat(this.map.get(3)).isEqualTo("3"); this.map.put(4, "4"); - assertThat(this.map.getSegment(0).getSize(), is(8)); - assertThat(this.map.get(4), is("4")); + assertThat(this.map.getSegment(0).getSize()).isEqualTo(8); + assertThat(this.map.get(4)).isEqualTo("4"); // Putting again should not increase the count for (int i = 1; i <= 5; i++) { this.map.put(i, String.valueOf(i)); } - assertThat(this.map.getSegment(0).getSize(), is(8)); - assertThat(this.map.get(5), is("5")); + assertThat(this.map.getSegment(0).getSize()).isEqualTo(8); + assertThat(this.map.get(5)).isEqualTo("5"); } @Test @@ -232,11 +228,11 @@ public class ConcurrentReferenceHashMapTests { } this.map.getMockReference(1, Restructure.NEVER).queueForPurge(); this.map.getMockReference(3, Restructure.NEVER).queueForPurge(); - assertThat(this.map.getReference(1, Restructure.WHEN_NECESSARY), is(nullValue())); - assertThat(this.map.get(2), is("2")); - assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY), is(nullValue())); - assertThat(this.map.get(4), is("4")); - assertThat(this.map.get(5), is("5")); + assertThat(this.map.getReference(1, Restructure.WHEN_NECESSARY)).isNull(); + assertThat(this.map.get(2)).isEqualTo("2"); + assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY)).isNull(); + assertThat(this.map.get(4)).isEqualTo("4"); + assertThat(this.map.get(5)).isEqualTo("5"); } @Test @@ -248,122 +244,122 @@ public class ConcurrentReferenceHashMapTests { this.map.getMockReference(1, Restructure.NEVER).queueForPurge(); this.map.getMockReference(3, Restructure.NEVER).queueForPurge(); this.map.put(1, "1"); - assertThat(this.map.get(1), is("1")); - assertThat(this.map.get(2), is("2")); - assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY), is(nullValue())); - assertThat(this.map.get(4), is("4")); - assertThat(this.map.get(5), is("5")); + assertThat(this.map.get(1)).isEqualTo("1"); + assertThat(this.map.get(2)).isEqualTo("2"); + assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY)).isNull(); + assertThat(this.map.get(4)).isEqualTo("4"); + assertThat(this.map.get(5)).isEqualTo("5"); } @Test public void shouldPutIfAbsent() { - assertThat(this.map.putIfAbsent(123, "123"), is(nullValue())); - assertThat(this.map.putIfAbsent(123, "123b"), is("123")); - assertThat(this.map.get(123), is("123")); + assertThat(this.map.putIfAbsent(123, "123")).isNull(); + assertThat(this.map.putIfAbsent(123, "123b")).isEqualTo("123"); + assertThat(this.map.get(123)).isEqualTo("123"); } @Test public void shouldPutIfAbsentWithNullValue() { - assertThat(this.map.putIfAbsent(123, null), is(nullValue())); - assertThat(this.map.putIfAbsent(123, "123"), is(nullValue())); - assertThat(this.map.get(123), is(nullValue())); + assertThat(this.map.putIfAbsent(123, null)).isNull(); + assertThat(this.map.putIfAbsent(123, "123")).isNull(); + assertThat(this.map.get(123)).isNull(); } @Test public void shouldPutIfAbsentWithNullKey() { - assertThat(this.map.putIfAbsent(null, "123"), is(nullValue())); - assertThat(this.map.putIfAbsent(null, "123b"), is("123")); - assertThat(this.map.get(null), is("123")); + assertThat(this.map.putIfAbsent(null, "123")).isNull(); + assertThat(this.map.putIfAbsent(null, "123b")).isEqualTo("123"); + assertThat(this.map.get(null)).isEqualTo("123"); } @Test public void shouldRemoveKeyAndValue() { this.map.put(123, "123"); - assertThat(this.map.remove(123, "456"), is(false)); - assertThat(this.map.get(123), is("123")); - assertThat(this.map.remove(123, "123"), is(true)); + assertThat(this.map.remove(123, "456")).isFalse(); + assertThat(this.map.get(123)).isEqualTo("123"); + assertThat(this.map.remove(123, "123")).isTrue(); assertFalse(this.map.containsKey(123)); - assertThat(this.map.isEmpty(), is(true)); + assertThat(this.map.isEmpty()).isTrue(); } @Test public void shouldRemoveKeyAndValueWithExistingNull() { this.map.put(123, null); - assertThat(this.map.remove(123, "456"), is(false)); - assertThat(this.map.get(123), is(nullValue())); - assertThat(this.map.remove(123, null), is(true)); + assertThat(this.map.remove(123, "456")).isFalse(); + assertThat(this.map.get(123)).isNull(); + assertThat(this.map.remove(123, null)).isTrue(); assertFalse(this.map.containsKey(123)); - assertThat(this.map.isEmpty(), is(true)); + assertThat(this.map.isEmpty()).isTrue(); } @Test public void shouldReplaceOldValueWithNewValue() { this.map.put(123, "123"); - assertThat(this.map.replace(123, "456", "789"), is(false)); - assertThat(this.map.get(123), is("123")); - assertThat(this.map.replace(123, "123", "789"), is(true)); - assertThat(this.map.get(123), is("789")); + assertThat(this.map.replace(123, "456", "789")).isFalse(); + assertThat(this.map.get(123)).isEqualTo("123"); + assertThat(this.map.replace(123, "123", "789")).isTrue(); + assertThat(this.map.get(123)).isEqualTo("789"); } @Test public void shouldReplaceOldNullValueWithNewValue() { this.map.put(123, null); - assertThat(this.map.replace(123, "456", "789"), is(false)); - assertThat(this.map.get(123), is(nullValue())); - assertThat(this.map.replace(123, null, "789"), is(true)); - assertThat(this.map.get(123), is("789")); + assertThat(this.map.replace(123, "456", "789")).isFalse(); + assertThat(this.map.get(123)).isNull(); + assertThat(this.map.replace(123, null, "789")).isTrue(); + assertThat(this.map.get(123)).isEqualTo("789"); } @Test public void shouldReplaceValue() { this.map.put(123, "123"); - assertThat(this.map.replace(123, "456"), is("123")); - assertThat(this.map.get(123), is("456")); + assertThat(this.map.replace(123, "456")).isEqualTo("123"); + assertThat(this.map.get(123)).isEqualTo("456"); } @Test public void shouldReplaceNullValue() { this.map.put(123, null); - assertThat(this.map.replace(123, "456"), is(nullValue())); - assertThat(this.map.get(123), is("456")); + assertThat(this.map.replace(123, "456")).isNull(); + assertThat(this.map.get(123)).isEqualTo("456"); } @Test public void shouldGetSize() { - assertThat(this.map.size(), is(0)); + assertThat(this.map).hasSize(0); this.map.put(123, "123"); this.map.put(123, null); this.map.put(456, "456"); - assertThat(this.map.size(), is(2)); + assertThat(this.map).hasSize(2); } @Test public void shouldSupportIsEmpty() { - assertThat(this.map.isEmpty(), is(true)); + assertThat(this.map.isEmpty()).isTrue(); this.map.put(123, "123"); this.map.put(123, null); this.map.put(456, "456"); - assertThat(this.map.isEmpty(), is(false)); + assertThat(this.map.isEmpty()).isFalse(); } @Test public void shouldContainKey() { - assertThat(this.map.containsKey(123), is(false)); - assertThat(this.map.containsKey(456), is(false)); + assertThat(this.map.containsKey(123)).isFalse(); + assertThat(this.map.containsKey(456)).isFalse(); this.map.put(123, "123"); this.map.put(456, null); - assertThat(this.map.containsKey(123), is(true)); - assertThat(this.map.containsKey(456), is(true)); + assertThat(this.map.containsKey(123)).isTrue(); + assertThat(this.map.containsKey(456)).isTrue(); } @Test public void shouldContainValue() { - assertThat(this.map.containsValue("123"), is(false)); - assertThat(this.map.containsValue(null), is(false)); + assertThat(this.map.containsValue("123")).isFalse(); + assertThat(this.map.containsValue(null)).isFalse(); this.map.put(123, "123"); this.map.put(456, null); - assertThat(this.map.containsValue("123"), is(true)); - assertThat(this.map.containsValue(null), is(true)); + assertThat(this.map.containsValue("123")).isTrue(); + assertThat(this.map.containsValue(null)).isTrue(); } @Test @@ -371,17 +367,17 @@ public class ConcurrentReferenceHashMapTests { this.map.put(123, null); this.map.put(456, "456"); this.map.put(null, "789"); - assertThat(this.map.remove(123), is(nullValue())); - assertThat(this.map.remove(456), is("456")); - assertThat(this.map.remove(null), is("789")); - assertThat(this.map.isEmpty(), is(true)); + assertThat(this.map.remove(123)).isNull(); + assertThat(this.map.remove(456)).isEqualTo("456"); + assertThat(this.map.remove(null)).isEqualTo("789"); + assertThat(this.map.isEmpty()).isTrue(); } @Test public void shouldRemoveWhenKeyIsNotInMap() { - assertThat(this.map.remove(123), is(nullValue())); - assertThat(this.map.remove(null), is(nullValue())); - assertThat(this.map.isEmpty(), is(true)); + assertThat(this.map.remove(123)).isNull(); + assertThat(this.map.remove(null)).isNull(); + assertThat(this.map.isEmpty()).isTrue(); } @Test @@ -391,10 +387,10 @@ public class ConcurrentReferenceHashMapTests { m.put(456, null); m.put(null, "789"); this.map.putAll(m); - assertThat(this.map.size(), is(3)); - assertThat(this.map.get(123), is("123")); - assertThat(this.map.get(456), is(nullValue())); - assertThat(this.map.get(null), is("789")); + assertThat(this.map).hasSize(3); + assertThat(this.map.get(123)).isEqualTo("123"); + assertThat(this.map.get(456)).isNull(); + assertThat(this.map.get(null)).isEqualTo("789"); } @Test @@ -403,10 +399,10 @@ public class ConcurrentReferenceHashMapTests { this.map.put(456, null); this.map.put(null, "789"); this.map.clear(); - assertThat(this.map.size(), is(0)); - assertThat(this.map.containsKey(123), is(false)); - assertThat(this.map.containsKey(456), is(false)); - assertThat(this.map.containsKey(null), is(false)); + assertThat(this.map).hasSize(0); + assertThat(this.map.containsKey(123)).isFalse(); + assertThat(this.map.containsKey(456)).isFalse(); + assertThat(this.map.containsKey(null)).isFalse(); } @Test @@ -418,7 +414,7 @@ public class ConcurrentReferenceHashMapTests { expected.add(123); expected.add(456); expected.add(null); - assertThat(this.map.keySet(), is(expected)); + assertThat(this.map.keySet()).isEqualTo(expected); } @Test @@ -433,7 +429,7 @@ public class ConcurrentReferenceHashMapTests { expected.add("789"); actual.sort(NULL_SAFE_STRING_SORT); expected.sort(NULL_SAFE_STRING_SORT); - assertThat(actual, is(expected)); + assertThat(actual).isEqualTo(expected); } @Test @@ -445,7 +441,7 @@ public class ConcurrentReferenceHashMapTests { expected.put(123, "123"); expected.put(456, null); expected.put(null, "789"); - assertThat(this.map.entrySet(), is(expected.entrySet())); + assertThat(this.map.entrySet()).isEqualTo(expected.entrySet()); } @Test @@ -459,7 +455,7 @@ public class ConcurrentReferenceHashMapTests { expected.put(1, "1"); expected.put(2, "2"); expected.put(3, "3"); - assertThat(this.map.entrySet(), is(expected.entrySet())); + assertThat(this.map.entrySet()).isEqualTo(expected.entrySet()); } @Test @@ -472,9 +468,9 @@ public class ConcurrentReferenceHashMapTests { iterator.next(); iterator.remove(); iterator.next(); - assertThat(iterator.hasNext(), is(false)); - assertThat(this.map.size(), is(2)); - assertThat(this.map.containsKey(2), is(false)); + assertThat(iterator.hasNext()).isFalse(); + assertThat(this.map).hasSize(2); + assertThat(this.map.containsKey(2)).isFalse(); } @Test @@ -486,9 +482,9 @@ public class ConcurrentReferenceHashMapTests { iterator.next(); iterator.next().setValue("2b"); iterator.next(); - assertThat(iterator.hasNext(), is(false)); - assertThat(this.map.size(), is(3)); - assertThat(this.map.get(2), is("2b")); + assertThat(iterator.hasNext()).isFalse(); + assertThat(this.map).hasSize(3); + assertThat(this.map.get(2)).isEqualTo("2b"); } @Test @@ -503,7 +499,7 @@ public class ConcurrentReferenceHashMapTests { System.out.println(cacheTime.prettyPrint()); // We should be at least 4 time faster - assertThat(cacheTime.getTotalTimeSeconds(), is(lessThan(mapTime.getTotalTimeSeconds() / 4.0))); + assertThat(cacheTime.getTotalTimeSeconds()).isLessThan(mapTime.getTotalTimeSeconds() / 4.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 de02da415a..a26a762d85 100644 --- a/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java @@ -26,9 +26,8 @@ import java.util.Set; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -789,23 +788,23 @@ public class ObjectUtilsTests { @Test public void containsConstant() { - assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO"), is(true)); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo"), is(true)); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "BaR"), is(true)); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "bar"), is(true)); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "BAZ"), is(true)); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "baz"), is(true)); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO")).isTrue(); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo")).isTrue(); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "BaR")).isTrue(); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "bar")).isTrue(); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "BAZ")).isTrue(); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "baz")).isTrue(); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "BOGUS"), is(false)); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "BOGUS")).isFalse(); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO", true), is(true)); - assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo", true), is(false)); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO", true)).isTrue(); + assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo", true)).isFalse(); } @Test public void caseInsensitiveValueOf() { - assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "foo"), is(Tropes.FOO)); - assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "BAR"), is(Tropes.BAR)); + assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "foo")).isEqualTo(Tropes.FOO); + assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "BAR")).isEqualTo(Tropes.BAR); assertThatIllegalArgumentException().isThrownBy(() -> ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "bogus")) 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 943b1f6873..ba18adc9fd 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -24,7 +24,6 @@ import java.rmi.RemoteException; import java.util.LinkedList; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; @@ -32,11 +31,8 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.tests.sample.objects.TestObject; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -288,7 +284,7 @@ public class ReflectionUtilsTests { toStringMethodCount++; } } - assertThat(toStringMethodCount, is(2)); + assertThat(toStringMethodCount).isEqualTo(2); } @Test @@ -305,7 +301,7 @@ public class ReflectionUtilsTests { toStringMethodCount++; } } - assertThat(toStringMethodCount, is(1)); + assertThat(toStringMethodCount).isEqualTo(1); } @Test @@ -329,7 +325,7 @@ public class ReflectionUtilsTests { m1MethodCount++; } } - assertThat(m1MethodCount, is(1)); + assertThat(m1MethodCount).isEqualTo(1); assertTrue(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1"))); assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1"))); } @@ -367,15 +363,15 @@ public class ReflectionUtilsTests { Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(C.class); sw.stop(); long totalMs = sw.getTotalTimeMillis(); - assertThat(methods.length, Matchers.greaterThan(100)); - assertThat(totalMs, Matchers.lessThan(10L)); + assertThat(methods.length).isGreaterThan(100); + assertThat(totalMs).isLessThan(10L); } @Test public void getDecalredMethodsReturnsCopy() { Method[] m1 = ReflectionUtils.getDeclaredMethods(A.class); Method[] m2 = ReflectionUtils.getDeclaredMethods(A.class); - assertThat(m1, not(sameInstance(m2))); + assertThat(m1). isNotSameAs(m2); } private static class ListSavingMethodCallback implements ReflectionUtils.MethodCallback { diff --git a/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java index 7c456ff446..eed4b32492 100644 --- a/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java @@ -29,8 +29,7 @@ import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -60,7 +59,7 @@ public class StreamUtilsTests { public void copyToByteArray() throws Exception { InputStream inputStream = spy(new ByteArrayInputStream(bytes)); byte[] actual = StreamUtils.copyToByteArray(inputStream); - assertThat(actual, equalTo(bytes)); + assertThat(actual).isEqualTo(bytes); verify(inputStream, never()).close(); } @@ -69,7 +68,7 @@ public class StreamUtilsTests { Charset charset = Charset.defaultCharset(); InputStream inputStream = spy(new ByteArrayInputStream(string.getBytes(charset))); String actual = StreamUtils.copyToString(inputStream, charset); - assertThat(actual, equalTo(string)); + assertThat(actual).isEqualTo(string); verify(inputStream, never()).close(); } @@ -77,7 +76,7 @@ public class StreamUtilsTests { public void copyBytes() throws Exception { ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); StreamUtils.copy(bytes, out); - assertThat(out.toByteArray(), equalTo(bytes)); + assertThat(out.toByteArray()).isEqualTo(bytes); verify(out, never()).close(); } @@ -86,7 +85,7 @@ public class StreamUtilsTests { Charset charset = Charset.defaultCharset(); ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); StreamUtils.copy(string, charset, out); - assertThat(out.toByteArray(), equalTo(string.getBytes(charset))); + assertThat(out.toByteArray()).isEqualTo(string.getBytes(charset)); verify(out, never()).close(); } @@ -94,7 +93,7 @@ public class StreamUtilsTests { public void copyStream() throws Exception { ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); StreamUtils.copy(new ByteArrayInputStream(bytes), out); - assertThat(out.toByteArray(), equalTo(bytes)); + assertThat(out.toByteArray()).isEqualTo(bytes); verify(out, never()).close(); } @@ -103,7 +102,7 @@ public class StreamUtilsTests { ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); StreamUtils.copyRange(new ByteArrayInputStream(bytes), out, 0, 100); byte[] range = Arrays.copyOfRange(bytes, 0, 101); - assertThat(out.toByteArray(), equalTo(range)); + assertThat(out.toByteArray()).isEqualTo(range); verify(out, never()).close(); } diff --git a/spring-core/src/test/java/org/springframework/util/comparator/BooleanComparatorTests.java b/spring-core/src/test/java/org/springframework/util/comparator/BooleanComparatorTests.java index 2192b2acc2..174309c36e 100644 --- a/spring-core/src/test/java/org/springframework/util/comparator/BooleanComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/util/comparator/BooleanComparatorTests.java @@ -20,8 +20,8 @@ import java.util.Comparator; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests for {@link BooleanComparator}. @@ -35,29 +35,29 @@ public class BooleanComparatorTests { @Test public void shouldCompareWithTrueLow() { Comparator c = new BooleanComparator(true); - assertThat(c.compare(true, false), is(-1)); - assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0)); + assertThat(c.compare(true, false)).isEqualTo(-1); + assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0); } @Test public void shouldCompareWithTrueHigh() { Comparator c = new BooleanComparator(false); - assertThat(c.compare(true, false), is(1)); - assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0)); + assertThat(c.compare(true, false)).isEqualTo(1); + assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0); } @Test public void shouldCompareFromTrueLow() { Comparator c = BooleanComparator.TRUE_LOW; - assertThat(c.compare(true, false), is(-1)); - assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0)); + assertThat(c.compare(true, false)).isEqualTo(-1); + assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0); } @Test public void shouldCompareFromTrueHigh() { Comparator c = BooleanComparator.TRUE_HIGH; - assertThat(c.compare(true, false), is(1)); - assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0)); + assertThat(c.compare(true, false)).isEqualTo(1); + assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0); } } diff --git a/spring-core/src/test/java/org/springframework/util/comparator/InstanceComparatorTests.java b/spring-core/src/test/java/org/springframework/util/comparator/InstanceComparatorTests.java index 400d464cf9..2efbc25de5 100644 --- a/spring-core/src/test/java/org/springframework/util/comparator/InstanceComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/util/comparator/InstanceComparatorTests.java @@ -20,8 +20,8 @@ import java.util.Comparator; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests for {@link InstanceComparator}. @@ -41,32 +41,32 @@ public class InstanceComparatorTests { @Test public void shouldCompareClasses() throws Exception { Comparator comparator = new InstanceComparator<>(C1.class, C2.class); - assertThat(comparator.compare(c1, c1), is(0)); - assertThat(comparator.compare(c1, c2), is(-1)); - assertThat(comparator.compare(c2, c1), is(1)); - assertThat(comparator.compare(c2, c3), is(-1)); - assertThat(comparator.compare(c2, c4), is(-1)); - assertThat(comparator.compare(c3, c4), is(0)); + assertThat(comparator.compare(c1, c1)).isEqualTo(0); + assertThat(comparator.compare(c1, c2)).isEqualTo(-1); + assertThat(comparator.compare(c2, c1)).isEqualTo(1); + assertThat(comparator.compare(c2, c3)).isEqualTo(-1); + assertThat(comparator.compare(c2, c4)).isEqualTo(-1); + assertThat(comparator.compare(c3, c4)).isEqualTo(0); } @Test public void shouldCompareInterfaces() throws Exception { Comparator comparator = new InstanceComparator<>(I1.class, I2.class); - assertThat(comparator.compare(c1, c1), is(0)); - assertThat(comparator.compare(c1, c2), is(0)); - assertThat(comparator.compare(c2, c1), is(0)); - assertThat(comparator.compare(c1, c3), is(-1)); - assertThat(comparator.compare(c3, c1), is(1)); - assertThat(comparator.compare(c3, c4), is(0)); + assertThat(comparator.compare(c1, c1)).isEqualTo(0); + assertThat(comparator.compare(c1, c2)).isEqualTo(0); + assertThat(comparator.compare(c2, c1)).isEqualTo(0); + assertThat(comparator.compare(c1, c3)).isEqualTo(-1); + assertThat(comparator.compare(c3, c1)).isEqualTo(1); + assertThat(comparator.compare(c3, c4)).isEqualTo(0); } @Test public void shouldCompareMix() throws Exception { Comparator comparator = new InstanceComparator<>(I1.class, C3.class); - assertThat(comparator.compare(c1, c1), is(0)); - assertThat(comparator.compare(c3, c4), is(-1)); - assertThat(comparator.compare(c3, null), is(-1)); - assertThat(comparator.compare(c4, null), is(0)); + assertThat(comparator.compare(c1, c1)).isEqualTo(0); + assertThat(comparator.compare(c3, c4)).isEqualTo(-1); + assertThat(comparator.compare(c3, null)).isEqualTo(-1); + assertThat(comparator.compare(c4, null)).isEqualTo(0); } private static interface I1 { diff --git a/spring-core/src/test/java/org/springframework/util/comparator/InvertibleComparatorTests.java b/spring-core/src/test/java/org/springframework/util/comparator/InvertibleComparatorTests.java index 25c6e653e2..2c077c7bc8 100644 --- a/spring-core/src/test/java/org/springframework/util/comparator/InvertibleComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/util/comparator/InvertibleComparatorTests.java @@ -20,9 +20,9 @@ import java.util.Comparator; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; + /** * Tests for {@link InvertibleComparator}. @@ -52,30 +52,30 @@ public class InvertibleComparatorTests { @Test public void shouldDefaultToAscending() throws Exception { InvertibleComparator invertibleComparator = new InvertibleComparator<>(comparator); - assertThat(invertibleComparator.isAscending(), is(true)); - assertThat(invertibleComparator.compare(1, 2), is(-1)); + assertThat(invertibleComparator.isAscending()).isTrue(); + assertThat(invertibleComparator.compare(1, 2)).isEqualTo(-1); } @Test public void shouldInvert() throws Exception { InvertibleComparator invertibleComparator = new InvertibleComparator<>(comparator); - assertThat(invertibleComparator.isAscending(), is(true)); - assertThat(invertibleComparator.compare(1, 2), is(-1)); + assertThat(invertibleComparator.isAscending()).isTrue(); + assertThat(invertibleComparator.compare(1, 2)).isEqualTo(-1); invertibleComparator.invertOrder(); - assertThat(invertibleComparator.isAscending(), is(false)); - assertThat(invertibleComparator.compare(1, 2), is(1)); + assertThat(invertibleComparator.isAscending()).isFalse(); + assertThat(invertibleComparator.compare(1, 2)).isEqualTo(1); } @Test public void shouldCompareAscending() throws Exception { InvertibleComparator invertibleComparator = new InvertibleComparator<>(comparator, true); - assertThat(invertibleComparator.compare(1, 2), is(-1)); + assertThat(invertibleComparator.compare(1, 2)).isEqualTo(-1); } @Test public void shouldCompareDescending() throws Exception { InvertibleComparator invertibleComparator = new InvertibleComparator<>(comparator, false); - assertThat(invertibleComparator.compare(1, 2), is(1)); + assertThat(invertibleComparator.compare(1, 2)).isEqualTo(1); } } diff --git a/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java b/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java index c8abc66b1f..709c8e1427 100644 --- a/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java +++ b/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java @@ -24,9 +24,8 @@ import java.util.concurrent.TimeoutException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -55,7 +54,7 @@ public class SettableListenableFutureTests { public void returnsSetValue() throws ExecutionException, InterruptedException { String string = "hello"; assertTrue(settableListenableFuture.set(string)); - assertThat(settableListenableFuture.get(), equalTo(string)); + assertThat(settableListenableFuture.get()).isEqualTo(string); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } @@ -65,7 +64,7 @@ public class SettableListenableFutureTests { String string = "hello"; assertTrue(settableListenableFuture.set(string)); Future completable = settableListenableFuture.completable(); - assertThat(completable.get(), equalTo(string)); + assertThat(completable.get()).isEqualTo(string); assertFalse(completable.isCancelled()); assertTrue(completable.isDone()); } @@ -148,7 +147,7 @@ public class SettableListenableFutureTests { }); settableListenableFuture.set(string); - assertThat(callbackHolder[0], equalTo(string)); + assertThat(callbackHolder[0]).isEqualTo(string); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } @@ -171,7 +170,7 @@ public class SettableListenableFutureTests { settableListenableFuture.set(string); assertFalse(settableListenableFuture.set("good bye")); - assertThat(callbackHolder[0], equalTo(string)); + assertThat(callbackHolder[0]).isEqualTo(string); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } @@ -193,7 +192,7 @@ public class SettableListenableFutureTests { }); settableListenableFuture.setException(exception); - assertThat(callbackHolder[0], equalTo(exception)); + assertThat(callbackHolder[0]).isEqualTo(exception); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } @@ -216,7 +215,7 @@ public class SettableListenableFutureTests { settableListenableFuture.setException(exception); assertFalse(settableListenableFuture.setException(new IllegalArgumentException())); - assertThat(callbackHolder[0], equalTo(exception)); + assertThat(callbackHolder[0]).isEqualTo(exception); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } @@ -247,7 +246,7 @@ public class SettableListenableFutureTests { }).start(); String value = settableListenableFuture.get(); - assertThat(value, equalTo(string)); + assertThat(value).isEqualTo(string); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } @@ -276,7 +275,7 @@ public class SettableListenableFutureTests { }).start(); String value = settableListenableFuture.get(500L, TimeUnit.MILLISECONDS); - assertThat(value, equalTo(string)); + assertThat(value).isEqualTo(string); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); } diff --git a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxHandlerTestCase.java b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxHandlerTestCase.java index fc5f5f8db4..4e5ac983eb 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxHandlerTestCase.java +++ b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxHandlerTestCase.java @@ -33,8 +33,9 @@ import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xmlunit.util.Predicate; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import org.springframework.tests.XmlContent; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -80,7 +81,7 @@ public abstract class AbstractStaxHandlerTestCase { xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML))); - assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter)); + assertThat(XmlContent.from(stringWriter)).isSimilarTo(COMPLEX_XML, nodeFilter); } @Test @@ -95,7 +96,7 @@ public abstract class AbstractStaxHandlerTestCase { xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML))); - assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter)); + assertThat(XmlContent.from(stringWriter)).isSimilarTo(COMPLEX_XML, nodeFilter); } @Test @@ -116,7 +117,7 @@ public abstract class AbstractStaxHandlerTestCase { xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML))); - assertThat(result, isSimilarTo(expected).withNodeFilter(nodeFilter)); + assertThat(XmlContent.of(result)).isSimilarTo(expected, nodeFilter); } @Test @@ -137,10 +138,9 @@ public abstract class AbstractStaxHandlerTestCase { xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML))); - assertThat(expected, isSimilarTo(result).withNodeFilter(nodeFilter)); + assertThat(XmlContent.of(result)).isSimilarTo(expected, nodeFilter); } - protected abstract AbstractStaxHandler createStaxHandler(Result result) throws XMLStreamException; } diff --git a/spring-core/src/test/java/org/springframework/util/xml/DomContentHandlerTests.java b/spring-core/src/test/java/org/springframework/util/xml/DomContentHandlerTests.java index aafe11ccc2..8ec0b90e79 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/DomContentHandlerTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/DomContentHandlerTests.java @@ -27,8 +27,9 @@ import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import org.springframework.tests.XmlContent; + +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DomContentHandler}. @@ -77,7 +78,7 @@ public class DomContentHandlerTests { expected = documentBuilder.parse(new InputSource(new StringReader(XML_1))); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(XML_1))); - assertThat("Invalid result", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected); } @Test @@ -86,7 +87,7 @@ public class DomContentHandlerTests { expected = documentBuilder.parse(new InputSource(new StringReader(XML_1))); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(XML_1))); - assertThat("Invalid result", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected); } @Test @@ -97,7 +98,7 @@ public class DomContentHandlerTests { expected = documentBuilder.parse(new InputSource(new StringReader(XML_2_EXPECTED))); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); - assertThat("Invalid result", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java index 356875abe3..9dc2c1acd0 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java @@ -29,14 +29,15 @@ import javax.xml.stream.events.XMLEvent; import org.junit.Test; +import org.springframework.tests.XmlContent; + import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.START_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -60,7 +61,7 @@ public class ListBasedXMLEventReaderTests { XMLEventWriter writer = this.outputFactory.createXMLEventWriter(resultWriter); writer.add(reader); - assertThat(resultWriter.toString(), isSimilarTo(xml)); + assertThat(XmlContent.from(resultWriter)).isSimilarTo(xml); } @Test 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 0470d5741b..ff6e2afa38 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 @@ -16,20 +16,17 @@ package org.springframework.util.xml; -import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedHashSet; import java.util.Set; import javax.xml.XMLConstants; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.anyOf; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; + /** * @author Arjen Poutsma @@ -56,23 +53,29 @@ public class SimpleNamespaceContextTests { @Test public void getNamespaceURI() { context.bindNamespaceUri(XMLConstants.XMLNS_ATTRIBUTE, additionalNamespaceUri); - assertThat("Always returns \"http://www.w3.org/2000/xmlns/\" for \"xmlns\"", - context.getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE), is(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)); + assertThat(context.getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE)) + .as("Always returns \"http://www.w3.org/2000/xmlns/\" for \"xmlns\"") + .isEqualTo(XMLConstants.XMLNS_ATTRIBUTE_NS_URI); context.bindNamespaceUri(XMLConstants.XML_NS_PREFIX, additionalNamespaceUri); - assertThat("Always returns \"http://www.w3.org/XML/1998/namespace\" for \"xml\"", - context.getNamespaceURI(XMLConstants.XML_NS_PREFIX), is(XMLConstants.XML_NS_URI)); + assertThat(context.getNamespaceURI(XMLConstants.XML_NS_PREFIX)) + .as("Always returns \"http://www.w3.org/XML/1998/namespace\" for \"xml\"") + .isEqualTo(XMLConstants.XML_NS_URI); - assertThat("Returns \"\" for an unbound prefix", context.getNamespaceURI(unboundPrefix), - is(XMLConstants.NULL_NS_URI)); + assertThat(context.getNamespaceURI(unboundPrefix)) + .as("Returns \"\" for an unbound prefix") + .isEqualTo(XMLConstants.NULL_NS_URI); context.bindNamespaceUri(prefix, namespaceUri); - assertThat("Returns the bound namespace URI for a bound prefix", context.getNamespaceURI(prefix), - is(namespaceUri)); + assertThat(context.getNamespaceURI(prefix)) + .as("Returns the bound namespace URI for a bound prefix") + .isEqualTo(namespaceUri); - assertThat("By default returns URI \"\" for the default namespace prefix", - context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX), is(XMLConstants.NULL_NS_URI)); + assertThat(context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)) + .as("By default returns URI \"\" for the default namespace prefix") + .isEqualTo(XMLConstants.NULL_NS_URI); context.bindDefaultNamespaceUri(defaultNamespaceUri); - assertThat("Returns the set URI for the default namespace prefix", - context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX), is(defaultNamespaceUri)); + assertThat(context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)) + .as("Returns the set URI for the default namespace prefix") + .isEqualTo(defaultNamespaceUri); } @Test @@ -83,17 +86,19 @@ public class SimpleNamespaceContextTests { @Test public void getPrefix() { - assertThat("Always returns \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"", - context.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI), is(XMLConstants.XMLNS_ATTRIBUTE)); - assertThat("Always returns \"xml\" for \"http://www.w3.org/XML/1998/namespace\"", - context.getPrefix(XMLConstants.XML_NS_URI), is(XMLConstants.XML_NS_PREFIX)); + assertThat(context.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) + .as("Always returns \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"") + .isEqualTo(XMLConstants.XMLNS_ATTRIBUTE); + assertThat(context.getPrefix(XMLConstants.XML_NS_URI)) + .as("Always returns \"xml\" for \"http://www.w3.org/XML/1998/namespace\"") + .isEqualTo(XMLConstants.XML_NS_PREFIX); - assertThat("Returns null for an unbound namespace URI", context.getPrefix(unboundNamespaceUri), - is(nullValue())); + assertThat(context.getPrefix(unboundNamespaceUri)).as("Returns null for an unbound namespace URI").isNull(); context.bindNamespaceUri("prefix1", namespaceUri); context.bindNamespaceUri("prefix2", namespaceUri); - assertThat("Returns a prefix for a bound namespace URI", context.getPrefix(namespaceUri), - anyOf(is("prefix1"), is("prefix2"))); + assertThat(context.getPrefix(namespaceUri)) + .as("Returns a prefix for a bound namespace URI") + .matches(prefix -> "prefix1".equals(prefix) || "prefix2".equals(prefix)); } @Test @@ -112,18 +117,21 @@ public class SimpleNamespaceContextTests { @Test public void getPrefixes() { - assertThat("Returns only \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"", - getItemSet(context.getPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)), - is(makeSet(XMLConstants.XMLNS_ATTRIBUTE))); - assertThat("Returns only \"xml\" for \"http://www.w3.org/XML/1998/namespace\"", - getItemSet(context.getPrefixes(XMLConstants.XML_NS_URI)), is(makeSet(XMLConstants.XML_NS_PREFIX))); + assertThat(getItemSet(context.getPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI))) + .as("Returns only \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"") + .containsExactly(XMLConstants.XMLNS_ATTRIBUTE); + assertThat(getItemSet(context.getPrefixes(XMLConstants.XML_NS_URI))) + .as("Returns only \"xml\" for \"http://www.w3.org/XML/1998/namespace\"") + .containsExactly(XMLConstants.XML_NS_PREFIX); - assertThat("Returns empty iterator for unbound prefix", context.getPrefixes("unbound Namespace URI").hasNext(), - is(false)); + assertThat(context.getPrefixes("unbound Namespace URI").hasNext()) + .as("Returns empty iterator for unbound prefix") + .isFalse(); context.bindNamespaceUri("prefix1", namespaceUri); context.bindNamespaceUri("prefix2", namespaceUri); - assertThat("Returns all prefixes (and only those) bound to the namespace URI", - getItemSet(context.getPrefixes(namespaceUri)), is(makeSet("prefix1", "prefix2"))); + assertThat(getItemSet(context.getPrefixes(namespaceUri))) + .as("Returns all prefixes (and only those) bound to the namespace URI") + .containsExactlyInAnyOrder("prefix1", "prefix2"); } @Test @@ -141,9 +149,12 @@ public class SimpleNamespaceContextTests { @Test public void bindNamespaceUri() { context.bindNamespaceUri(prefix, namespaceUri); - assertThat("The Namespace URI was bound to the prefix", context.getNamespaceURI(prefix), is(namespaceUri)); - assertThat("The prefix was bound to the namespace URI", getItemSet(context.getPrefixes(namespaceUri)), - hasItem(prefix)); + assertThat(context.getNamespaceURI(prefix)) + .as("The Namespace URI was bound to the prefix") + .isEqualTo(namespaceUri); + assertThat(getItemSet(context.getPrefixes(namespaceUri))) + .as("The prefix was bound to the namespace URI") + .contains(prefix); } @Test @@ -151,8 +162,9 @@ public class SimpleNamespaceContextTests { context.bindNamespaceUri("prefix1", namespaceUri); context.bindNamespaceUri("prefix2", namespaceUri); context.bindNamespaceUri("prefix3", additionalNamespaceUri); - assertThat("Returns all bound prefixes", getItemSet(context.getBoundPrefixes()), - is(makeSet("prefix1", "prefix2", "prefix3"))); + assertThat(getItemSet(context.getBoundPrefixes())) + .as("Returns all bound prefixes") + .containsExactlyInAnyOrder("prefix1", "prefix2", "prefix3"); } @Test @@ -161,8 +173,8 @@ public class SimpleNamespaceContextTests { context.bindNamespaceUri("prefix2", namespaceUri); context.bindNamespaceUri("prefix3", additionalNamespaceUri); context.clear(); - assertThat("All bound prefixes were removed", context.getBoundPrefixes().hasNext(), is(false)); - assertThat("All bound namespace URIs were removed", context.getPrefixes(namespaceUri).hasNext(), is(false)); + assertThat(context.getBoundPrefixes().hasNext()).as("All bound prefixes were removed").isFalse(); + assertThat(context.getPrefixes(namespaceUri).hasNext()).as("All bound namespace URIs were removed").isFalse(); } @Test @@ -171,37 +183,24 @@ public class SimpleNamespaceContextTests { context.bindNamespaceUri(prefix, namespaceUri); context.removeBinding(prefix); - assertThat("Returns default namespace URI for removed prefix", context.getNamespaceURI(prefix), - is(XMLConstants.NULL_NS_URI)); - assertThat("#getPrefix returns null when all prefixes for a namespace URI were removed", - context.getPrefix(namespaceUri), is(nullValue())); - assertThat("#getPrefixes returns an empty iterator when all prefixes for a namespace URI were removed", - context.getPrefixes(namespaceUri).hasNext(), is(false)); + assertThat(context.getNamespaceURI(prefix)).as("Returns default namespace URI for removed prefix").isEqualTo(XMLConstants.NULL_NS_URI); + 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("Prefix was unbound", context.getNamespaceURI("prefix1"), is(XMLConstants.NULL_NS_URI)); - assertThat("#getPrefix returns a bound prefix after removal of another prefix for the same namespace URI", - context.getPrefix(additionalNamespaceUri), is("prefix2")); - assertThat("Prefix was removed from namespace URI", getItemSet(context.getPrefixes(additionalNamespaceUri)), - is(makeSet("prefix2"))); + assertThat(context.getNamespaceURI("prefix1")).as("Prefix was unbound").isEqualTo(XMLConstants.NULL_NS_URI); + 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") + .containsExactly("prefix2"); } private Set getItemSet(Iterator iterator) { - Set itemSet = new HashSet<>(); - while (iterator.hasNext()) { - itemSet.add(iterator.next()); - } - return itemSet; - } - - private Set makeSet(String... items) { - Set itemSet = new HashSet<>(); - for (String item : items) { - itemSet.add(item); - } + Set itemSet = new LinkedHashSet<>(); + iterator.forEachRemaining(itemSet::add); return itemSet; } diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java index b3ecdeb28b..bdf7daf425 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java @@ -30,10 +30,11 @@ import javax.xml.transform.stream.StreamSource; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; +import org.springframework.tests.XmlContent; + +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -63,7 +64,7 @@ public class StaxResultTests { assertEquals("Invalid streamWriter returned", streamWriter, result.getXMLStreamWriter()); assertNull("EventWriter returned", result.getXMLEventWriter()); transformer.transform(source, result); - assertThat("Invalid result", stringWriter.toString(), isSimilarTo(XML)); + assertThat(XmlContent.from(stringWriter)).as("Invalid result").isSimilarTo(XML); } @Test @@ -76,7 +77,7 @@ public class StaxResultTests { assertEquals("Invalid eventWriter returned", eventWriter, result.getXMLEventWriter()); assertNull("StreamWriter returned", result.getXMLStreamWriter()); transformer.transform(source, result); - assertThat("Invalid result", stringWriter.toString(), isSimilarTo(XML)); + assertThat(XmlContent.from(stringWriter)).as("Invalid result").isSimilarTo(XML); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java index 6c22e22714..fbe840bdc0 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java @@ -33,10 +33,11 @@ import org.junit.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import static org.hamcrest.MatcherAssert.assertThat; +import org.springframework.tests.XmlContent; + +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -69,7 +70,7 @@ public class StaxSourceTests { assertNull("EventReader returned", source.getXMLEventReader()); StringWriter writer = new StringWriter(); transformer.transform(source, new StreamResult(writer)); - assertThat("Invalid result", writer.toString(), isSimilarTo(XML)); + assertThat(XmlContent.from(writer)).as("Invalid result").isSimilarTo(XML); } @Test @@ -82,7 +83,7 @@ public class StaxSourceTests { Document expected = documentBuilder.parse(new InputSource(new StringReader(XML))); Document result = documentBuilder.newDocument(); transformer.transform(source, new DOMResult(result)); - assertThat("Invalid result", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected); } @Test @@ -93,7 +94,7 @@ public class StaxSourceTests { assertNull("StreamReader returned", source.getXMLStreamReader()); StringWriter writer = new StringWriter(); transformer.transform(source, new StreamResult(writer)); - assertThat("Invalid result", writer.toString(), isSimilarTo(XML)); + assertThat(XmlContent.from(writer)).as("Invalid result").isSimilarTo(XML); } @Test @@ -106,6 +107,6 @@ public class StaxSourceTests { Document expected = documentBuilder.parse(new InputSource(new StringReader(XML))); Document result = documentBuilder.newDocument(); transformer.transform(source, new DOMResult(result)); - assertThat("Invalid result", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamReaderTests.java index a57faff73b..001d11285e 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamReaderTests.java @@ -30,8 +30,9 @@ import org.junit.Test; import org.w3c.dom.Node; import org.xmlunit.util.Predicate; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import org.springframework.tests.XmlContent; + +import static org.assertj.core.api.Assertions.assertThat; public class XMLEventStreamReaderTests { @@ -63,7 +64,7 @@ public class XMLEventStreamReaderTests { transformer.transform(source, new StreamResult(writer)); Predicate nodeFilter = n -> n.getNodeType() != Node.DOCUMENT_TYPE_NODE && n.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE; - assertThat(writer.toString(), isSimilarTo(XML).withNodeFilter(nodeFilter)); + assertThat(XmlContent.from(writer)).isSimilarTo(XML, nodeFilter); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamWriterTests.java b/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamWriterTests.java index 1040778193..4d399e7987 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamWriterTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamWriterTests.java @@ -26,8 +26,9 @@ import org.junit.Test; import org.w3c.dom.Node; import org.xmlunit.util.Predicate; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import org.springframework.tests.XmlContent; + +import static org.assertj.core.api.Assertions.assertThat; public class XMLEventStreamWriterTests { @@ -61,7 +62,7 @@ public class XMLEventStreamWriterTests { streamWriter.writeEndDocument(); Predicate nodeFilter = n -> n.getNodeType() != Node.DOCUMENT_TYPE_NODE && n.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE; - assertThat(stringWriter.toString(), isSimilarTo(XML).withNodeFilter(nodeFilter)); + assertThat(XmlContent.from(stringWriter)).isSimilarTo(XML, nodeFilter); } 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 80ad495f3b..2077e6628b 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java @@ -45,8 +45,6 @@ import org.springframework.expression.spel.testresources.TestPerson; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -671,14 +669,14 @@ public class EvaluationTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser( new SpelParserConfiguration(true, true, 3)); Expression e = parser.parseExpression("foo[2]"); e.setValue(ctx, "2"); - assertThat(instance.getFoo().size(), equalTo(3)); + assertThat(instance.getFoo().size()).isEqualTo(3); e = parser.parseExpression("foo[3]"); try { e.setValue(ctx, "3"); } catch (SpelEvaluationException see) { assertEquals(SpelMessage.UNABLE_TO_GROW_COLLECTION, see.getMessageCode()); - assertThat(instance.getFoo().size(), equalTo(3)); + assertThat(instance.getFoo().size()).isEqualTo(3); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java index cd3bbe7429..89aab2f844 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java @@ -33,8 +33,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.util.StopWatch; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.lessThan; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -116,7 +115,7 @@ public class MapAccessTests extends AbstractExpressionTests { expr.getValue(context); } s.stop(); - assertThat(s.getTotalTimeMillis(), lessThan(200L)); + assertThat(s.getTotalTimeMillis()).isLessThan(200L); } 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 a22fe2e9c6..06b8dd80c6 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -63,9 +63,6 @@ import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -1261,10 +1258,10 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); String fromInterface = parser.parseExpression("T(" + StaticFinalImpl1.class.getName() + ").VALUE").getValue( context, String.class); - assertThat(fromInterface, is("interfaceValue")); + assertThat(fromInterface).isEqualTo("interfaceValue"); String fromClass = parser.parseExpression("T(" + StaticFinalImpl2.class.getName() + ").VALUE").getValue( context, String.class); - assertThat(fromClass, is("interfaceValue")); + assertThat(fromClass).isEqualTo("interfaceValue"); } @Test @@ -1359,8 +1356,8 @@ public class SpelReproTests extends AbstractExpressionTests { Spr10486 rootObject = new Spr10486(); Expression classNameExpression = parser.parseExpression("class.name"); Expression nameExpression = parser.parseExpression("name"); - assertThat(classNameExpression.getValue(context, rootObject), equalTo((Object) Spr10486.class.getName())); - assertThat(nameExpression.getValue(context, rootObject), equalTo((Object) "name")); + assertThat(classNameExpression.getValue(context, rootObject)).isEqualTo(Spr10486.class.getName()); + assertThat(nameExpression.getValue(context, rootObject)).isEqualTo("name"); } @Test @@ -1424,7 +1421,7 @@ public class SpelReproTests extends AbstractExpressionTests { public void SPR11494() { Expression exp = new SpelExpressionParser().parseExpression("T(java.util.Arrays).asList('a','b')"); List list = (List) exp.getValue(); - assertThat(list.size(), is(2)); + assertThat(list).hasSize(2); } @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 6cb805af44..16bf08db0d 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 @@ -36,11 +36,8 @@ import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.DEFAULT_DATABASE_NAME; @@ -184,8 +181,8 @@ public class JdbcNamespaceIntegrationTests { private void assertBeanPropertyValueOf(String propertyName, String expected, DefaultListableBeanFactory factory) { BeanDefinition bean = factory.getBeanDefinition(expected); PropertyValue value = bean.getPropertyValues().getPropertyValue(propertyName); - assertThat(value, is(notNullValue())); - assertThat(value.getValue().toString(), is(expected)); + assertThat(value).isNotNull(); + assertThat(value.getValue().toString()).isEqualTo(expected); } private void assertNumRowsInTestTable(JdbcTemplate template, int count) { @@ -204,7 +201,7 @@ public class JdbcNamespaceIntegrationTests { assertNumRowsInTestTable(new JdbcTemplate(dataSource), count); assertTrue(dataSource instanceof AbstractDriverBasedDataSource); AbstractDriverBasedDataSource adbDataSource = (AbstractDriverBasedDataSource) dataSource; - assertThat(adbDataSource.getUrl(), containsString(dataSourceName)); + assertThat(adbDataSource.getUrl()).contains(dataSourceName); } } finally { 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 34218314c6..183abbf8e5 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 @@ -52,10 +52,8 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.util.LinkedCaseInsensitiveMap; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -440,7 +438,7 @@ public class JdbcTemplateTests { template.batchUpdate(sql); } catch (UncategorizedSQLException ex) { - assertThat(ex.getSql(), equalTo("B; D")); + assertThat(ex.getSql()).isEqualTo("B; D"); } } @@ -1069,7 +1067,7 @@ public class JdbcTemplateTests { Map out = this.template.call( conn -> conn.prepareCall("my query"), Collections.singletonList(new SqlOutParameter("a", 12))); - assertThat(out, instanceOf(LinkedCaseInsensitiveMap.class)); + assertThat(out).isInstanceOf(LinkedCaseInsensitiveMap.class); assertNotNull("we should have gotten the result with upper case", out.get("A")); assertNotNull("we should have gotten the result with lower case", out.get("a")); verify(this.callableStatement).close(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java index d94a477ecd..a51865c5f0 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java @@ -19,13 +19,12 @@ package org.springframework.jdbc.core.namedparam; import java.sql.Types; import java.util.Arrays; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -94,35 +93,32 @@ public class BeanPropertySqlParameterSourceTests { @Test public void toStringShowsParameterDetails() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); - assertThat(source.toString(), Matchers.allOf( - Matchers.startsWith("BeanPropertySqlParameterSource {"), - Matchers.endsWith("}"), - Matchers.containsString("name=tb (type:VARCHAR)"), - Matchers.containsString("age=99 (type:INTEGER)") - )); + assertThat(source.toString()) + .startsWith("BeanPropertySqlParameterSource {") + .contains("name=tb (type:VARCHAR)") + .contains("age=99 (type:INTEGER)") + .endsWith("}"); } @Test public void toStringShowsCustomSqlType() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); source.registerSqlType("name", Integer.MAX_VALUE); - assertThat(source.toString(), Matchers.allOf( - Matchers.startsWith("BeanPropertySqlParameterSource {"), - Matchers.endsWith("}"), - Matchers.containsString("name=tb (type:" + Integer.MAX_VALUE + ")"), - Matchers.containsString("age=99 (type:INTEGER)") - )); + assertThat(source.toString()) + .startsWith("BeanPropertySqlParameterSource {") + .contains("name=tb (type:" + Integer.MAX_VALUE + ")") + .contains("age=99 (type:INTEGER)") + .endsWith("}"); } @Test public void toStringDoesNotShowTypeUnknown() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); - assertThat(source.toString(), Matchers.allOf( - Matchers.startsWith("BeanPropertySqlParameterSource {"), - Matchers.endsWith("}"), - Matchers.containsString("beanFactory=null"), - Matchers.not(Matchers.containsString("beanFactory=null (type:")) - )); + assertThat(source.toString()) + .startsWith("BeanPropertySqlParameterSource {") + .contains("beanFactory=null") + .doesNotContain("beanFactory=null (type:") + .endsWith("}"); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java index b5a4b6bdbc..bf93d7a2fc 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java @@ -32,9 +32,8 @@ import org.mockito.MockitoAnnotations; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -113,7 +112,7 @@ public class SqlLobValueTests { verify(creator).setClobAsAsciiStream(eq(preparedStatement), eq(1), inputStreamCaptor.capture(), eq(3)); byte[] bytes = new byte[3]; inputStreamCaptor.getValue().read(bytes); - assertThat(bytes, equalTo(testContent)); + assertThat(bytes).isEqualTo(testContent); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java index 41866db711..e238eb07d6 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java @@ -23,8 +23,7 @@ import javax.sql.DataSource; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -44,7 +43,7 @@ public class DelegatingDataSourceTests { public void shouldDelegateGetConnection() throws Exception { Connection connection = mock(Connection.class); given(delegate.getConnection()).willReturn(connection); - assertThat(dataSource.getConnection(), is(connection)); + assertThat(dataSource.getConnection()).isEqualTo(connection); } @Test @@ -53,14 +52,14 @@ public class DelegatingDataSourceTests { String username = "username"; String password = "password"; given(delegate.getConnection(username, password)).willReturn(connection); - assertThat(dataSource.getConnection(username, password), is(connection)); + assertThat(dataSource.getConnection(username, password)).isEqualTo(connection); } @Test public void shouldDelegateGetLogWriter() throws Exception { PrintWriter writer = new PrintWriter(new ByteArrayOutputStream()); given(delegate.getLogWriter()).willReturn(writer); - assertThat(dataSource.getLogWriter(), is(writer)); + assertThat(dataSource.getLogWriter()).isEqualTo(writer); } @Test @@ -74,7 +73,7 @@ public class DelegatingDataSourceTests { public void shouldDelegateGetLoginTimeout() throws Exception { int timeout = 123; given(delegate.getLoginTimeout()).willReturn(timeout); - assertThat(dataSource.getLoginTimeout(), is(timeout)); + assertThat(dataSource.getLoginTimeout()).isEqualTo(timeout); } @Test @@ -88,26 +87,25 @@ public class DelegatingDataSourceTests { public void shouldDelegateUnwrapWithoutImplementing() throws Exception { ExampleWrapper wrapper = mock(ExampleWrapper.class); given(delegate.unwrap(ExampleWrapper.class)).willReturn(wrapper); - assertThat(dataSource.unwrap(ExampleWrapper.class), is(wrapper)); + assertThat(dataSource.unwrap(ExampleWrapper.class)).isEqualTo(wrapper); } @Test public void shouldDelegateUnwrapImplementing() throws Exception { dataSource = new DelegatingDataSourceWithWrapper(); - assertThat(dataSource.unwrap(ExampleWrapper.class), - is((ExampleWrapper) dataSource)); + assertThat(dataSource.unwrap(ExampleWrapper.class)).isSameAs(dataSource); } @Test public void shouldDelegateIsWrapperForWithoutImplementing() throws Exception { given(delegate.isWrapperFor(ExampleWrapper.class)).willReturn(true); - assertThat(dataSource.isWrapperFor(ExampleWrapper.class), is(true)); + assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue(); } @Test public void shouldDelegateIsWrapperForImplementing() throws Exception { dataSource = new DelegatingDataSourceWithWrapper(); - assertThat(dataSource.isWrapperFor(ExampleWrapper.class), is(true)); + assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue(); } public static interface ExampleWrapper { diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java index 09f7e68c7f..6c2e9dd360 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java @@ -27,8 +27,9 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.transaction.support.TransactionSynchronizationManager; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; + + /** * Abstract base class for integration tests involving database initialization. @@ -76,9 +77,9 @@ public abstract class AbstractDatabaseInitializationTests { void assertUsersDatabaseCreated(String... lastNames) { for (String lastName : lastNames) { - assertThat("Did not find user with last name [" + lastName + "].", - jdbcTemplate.queryForObject("select count(0) from users where last_name = ?", Integer.class, lastName), - equalTo(1)); + String sql = "select count(0) from users where last_name = ?"; + Integer result = jdbcTemplate.queryForObject(sql, Integer.class, lastName); + assertThat(result).as("user with last name [" + lastName + "]").isEqualTo(1); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java index 393a10e56a..f0b033bd38 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.transaction.support.TransactionSynchronizationManager; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -40,6 +39,10 @@ import static org.mockito.Mockito.verify; */ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializationTests { + private static final String COUNT_DAVE_SQL = "select COUNT(NAME) from T_TEST where NAME='Dave'"; + + private static final String COUNT_KEITH_SQL = "select COUNT(NAME) from T_TEST where NAME='Keith'"; + protected final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); @@ -73,10 +76,8 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(resource("db-test-data-multiple.sql")); DatabasePopulatorUtils.execute(databasePopulator, db); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), - equalTo(1)); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), - equalTo(1)); + assertThat(jdbcTemplate.queryForObject(COUNT_KEITH_SQL, Integer.class)).isEqualTo(1); + assertThat(jdbcTemplate.queryForObject(COUNT_DAVE_SQL, Integer.class)).isEqualTo(1); } @Test @@ -85,10 +86,8 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni databasePopulator.addScript(resource("db-test-data-endings.sql")); databasePopulator.setSeparator("@@"); DatabasePopulatorUtils.execute(databasePopulator, db); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), - equalTo(1)); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), - equalTo(1)); + assertThat(jdbcTemplate.queryForObject(COUNT_KEITH_SQL, Integer.class)).isEqualTo(1); + assertThat(jdbcTemplate.queryForObject(COUNT_DAVE_SQL, Integer.class)).isEqualTo(1); } @Test @@ -97,10 +96,8 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni databasePopulator.addScript(resource("db-test-data-whitespace.sql")); databasePopulator.setSeparator("/\n"); DatabasePopulatorUtils.execute(databasePopulator, db); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), - equalTo(1)); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), - equalTo(1)); + assertThat(jdbcTemplate.queryForObject(COUNT_KEITH_SQL, Integer.class)).isEqualTo(1); + assertThat(jdbcTemplate.queryForObject(COUNT_DAVE_SQL, Integer.class)).isEqualTo(1); } @Test @@ -108,10 +105,8 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(resource("db-test-data-newline.sql")); DatabasePopulatorUtils.execute(databasePopulator, db); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), - equalTo(1)); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), - equalTo(1)); + assertThat(jdbcTemplate.queryForObject(COUNT_KEITH_SQL, Integer.class)).isEqualTo(1); + assertThat(jdbcTemplate.queryForObject(COUNT_DAVE_SQL, Integer.class)).isEqualTo(1); } @Test @@ -120,10 +115,8 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni databasePopulator.addScript(resource("db-test-data-multi-newline.sql")); databasePopulator.setSeparator("\n\n"); DatabasePopulatorUtils.execute(databasePopulator, db); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), - equalTo(1)); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), - equalTo(1)); + assertThat(jdbcTemplate.queryForObject(COUNT_KEITH_SQL, Integer.class)).isEqualTo(1); + assertThat(jdbcTemplate.queryForObject(COUNT_DAVE_SQL, Integer.class)).isEqualTo(1); } @Test @@ -166,10 +159,8 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(resource("db-test-data-select.sql")); DatabasePopulatorUtils.execute(databasePopulator, db); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), - equalTo(1)); - assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), - equalTo(1)); + assertThat(jdbcTemplate.queryForObject(COUNT_KEITH_SQL, Integer.class)).isEqualTo(1); + assertThat(jdbcTemplate.queryForObject(COUNT_DAVE_SQL, Integer.class)).isEqualTo(1); } /** diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java index 7a4ccd63b1..1c5b49c404 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java @@ -20,8 +20,9 @@ import org.junit.Test; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; + + /** * @author Sam Brannen @@ -48,7 +49,7 @@ public class H2DatabasePopulatorTests extends AbstractDatabasePopulatorTests { databasePopulator.setSeparator("\n\n"); DatabasePopulatorUtils.execute(databasePopulator, db); String sql = "select REVERSE(first_name) from users where last_name='Brannen'"; - assertThat(jdbcTemplate.queryForObject(sql, String.class), equalTo("maS")); + assertThat(jdbcTemplate.queryForObject(sql, String.class)).isEqualTo("maS"); } } 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 b7ff88c809..0c54377cb9 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 @@ -39,10 +39,8 @@ import org.springframework.jdbc.core.SqlParameter; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; @@ -124,7 +122,7 @@ public class SqlQueryTests { query.compile(); List list = query.execute(); - assertThat(list, is(equalTo(Arrays.asList(1)))); + assertThat(list).isEqualTo(Arrays.asList(1)); verify(connection).prepareStatement(SELECT_ID); verify(resultSet).close(); verify(preparedStatement).close(); @@ -174,7 +172,7 @@ public class SqlQueryTests { StringQuery query = new StringQuery(dataSource, SELECT_FORENAME); query.setRowsExpected(3); String[] results = query.run(); - assertThat(results, is(equalTo(dbResults))); + assertThat(results).isEqualTo(dbResults); verify(connection).prepareStatement(SELECT_FORENAME); verify(resultSet).close(); verify(preparedStatement).close(); @@ -186,7 +184,7 @@ public class SqlQueryTests { given(resultSet.next()).willReturn(false); StringQuery query = new StringQuery(dataSource, SELECT_FORENAME_EMPTY); String[] results = query.run(); - assertThat(results, is(equalTo(new String[0]))); + assertThat(results).isEqualTo(new String[0]); verify(connection).prepareStatement(SELECT_FORENAME_EMPTY); verify(resultSet).close(); verify(preparedStatement).close(); @@ -392,8 +390,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List list = query.execute(1, 1); assertTrue("2 results in list", list.size() == 2); - assertThat(list.get(0).getForename(), is("rod")); - assertThat(list.get(1).getForename(), is("dave")); + assertThat(list.get(0).getForename()).isEqualTo("rod"); + assertThat(list.get(1).getForename()).isEqualTo("dave"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC); verify(connection).prepareStatement(SELECT_ID_WHERE); @@ -428,8 +426,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List list = query.execute("one"); assertTrue("2 results in list", list.size() == 2); - assertThat(list.get(0).getForename(), is("rod")); - assertThat(list.get(1).getForename(), is("dave")); + assertThat(list.get(0).getForename()).isEqualTo("rod"); + assertThat(list.get(1).getForename()).isEqualTo("dave"); verify(preparedStatement).setString(1, "one"); verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE); verify(resultSet).close(); 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 a754e04fdb..216345bec7 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 @@ -27,8 +27,7 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -76,7 +75,7 @@ public class SQLErrorCodesFactoryTests { } private void assertIsSQLServer(SQLErrorCodes sec) { - assertThat(sec.getDatabaseProductName(), equalTo("Microsoft SQL Server")); + assertThat(sec.getDatabaseProductName()).isEqualTo("Microsoft SQL Server"); assertTrue(sec.getBadSqlGrammarCodes().length > 0); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java index 40f71beb6e..84319166df 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java @@ -24,8 +24,7 @@ import org.springframework.dao.DataAccessException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -52,7 +51,7 @@ public class SQLExceptionCustomTranslatorTests { SQLException badSqlGrammarExceptionEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1); DataAccessException dae = sext.translate("task", "SQL", badSqlGrammarExceptionEx); assertEquals(badSqlGrammarExceptionEx, dae.getCause()); - assertThat(dae, instanceOf(BadSqlGrammarException.class)); + assertThat(dae).isInstanceOf(BadSqlGrammarException.class); } @Test @@ -60,7 +59,7 @@ public class SQLExceptionCustomTranslatorTests { SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2); DataAccessException dae = sext.translate("task", "SQL", dataAccessResourceEx); assertEquals(dataAccessResourceEx, dae.getCause()); - assertThat(dae, instanceOf(TransientDataAccessResourceException.class)); + assertThat(dae).isInstanceOf(TransientDataAccessResourceException.class); } } diff --git a/spring-messaging/spring-messaging.gradle b/spring-messaging/spring-messaging.gradle index b6ceb7cedf..ba6b40b5fa 100644 --- a/spring-messaging/spring-messaging.gradle +++ b/spring-messaging/spring-messaging.gradle @@ -35,6 +35,7 @@ dependencies { testCompile "io.reactivex.rxjava2:rxjava:${rxjava2Version}" testCompile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") testCompile("org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}") + testCompile("org.xmlunit:xmlunit-assertj:2.6.2") testCompile("org.xmlunit:xmlunit-matchers:2.6.2") testCompile(project(":spring-core-coroutines")) testRuntime("com.sun.xml.bind:jaxb-core:2.3.0.1") 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 44d010d0ba..ff11926e6f 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 @@ -33,11 +33,8 @@ import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.MimeType; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -57,8 +54,8 @@ public class MappingJackson2MessageConverterTests { @Test public void defaultConstructor() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); - assertThat(converter.getSupportedMimeTypes(), - contains(new MimeType("application", "json"))); + assertThat(converter.getSupportedMimeTypes()) + .contains(new MimeType("application", "json")); assertFalse(converter.getObjectMapper().getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); } @@ -67,7 +64,7 @@ public class MappingJackson2MessageConverterTests { public void mimetypeParametrizedConstructor() { MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype); - assertThat(converter.getSupportedMimeTypes(), contains(mimetype)); + assertThat(converter.getSupportedMimeTypes()).contains(mimetype); assertFalse(converter.getObjectMapper().getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); } @@ -77,7 +74,7 @@ public class MappingJackson2MessageConverterTests { MimeType jsonMimetype = new MimeType("application", "json", StandardCharsets.UTF_8); MimeType xmlMimetype = new MimeType("application", "xml", StandardCharsets.UTF_8); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype); - assertThat(converter.getSupportedMimeTypes(), contains(jsonMimetype, xmlMimetype)); + assertThat(converter.getSupportedMimeTypes()).contains(jsonMimetype, xmlMimetype); assertFalse(converter.getObjectMapper().getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); } @@ -238,9 +235,9 @@ public class MappingJackson2MessageConverterTests { Message message = converter.toMessage(jsonViewResponse(), new MessageHeaders(map), returnType); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); - assertThat(actual, containsString("\"withView1\":\"with\"")); - assertThat(actual, containsString("\"withView2\":\"with\"")); - assertThat(actual, not(containsString("\"withoutView\":\"with\""))); + assertThat(actual).contains("\"withView1\":\"with\""); + assertThat(actual).contains("\"withView2\":\"with\""); + assertThat(actual).doesNotContain("\"withoutView\":\"with\""); method = getClass().getDeclaredMethod("jsonViewPayload", JacksonViewBean.class); MethodParameter param = new MethodParameter(method, 0); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java index f54fadf84e..40631c1fe2 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java @@ -27,16 +27,16 @@ import org.xmlunit.diff.DifferenceEvaluator; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.tests.XmlContent; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.xmlunit.diff.ComparisonType.XML_STANDALONE; import static org.xmlunit.diff.DifferenceEvaluators.Default; import static org.xmlunit.diff.DifferenceEvaluators.chain; import static org.xmlunit.diff.DifferenceEvaluators.downgradeDifferencesToEqual; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -92,7 +92,7 @@ public class MarshallingMessageConverterTests { String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); - assertThat(actual, isSimilarTo("Foo").withDifferenceEvaluator(ev)); + assertThat(XmlContent.of(actual)).isSimilarTo("Foo", ev); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java index 4ec4080e0a..0ef4b074f7 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; @@ -41,8 +40,8 @@ import org.springframework.util.AntPathMatcher; import org.springframework.util.Assert; import org.springframework.util.PathMatcher; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -88,7 +87,7 @@ public class MethodMessageHandlerTests { Map handlerMethods = this.messageHandler.getHandlerMethods(); assertNotNull(handlerMethods); - assertThat(handlerMethods.keySet(), Matchers.hasSize(3)); + assertThat(handlerMethods).hasSize(3); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java index 5d796b2492..1c61fd2a43 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java @@ -26,7 +26,6 @@ import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; -import org.hamcrest.Matchers; import org.junit.Test; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; @@ -47,8 +46,8 @@ import org.springframework.util.PathMatcher; import org.springframework.util.RouteMatcher; import org.springframework.util.SimpleRouteMatcher; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; /** @@ -70,9 +69,9 @@ public class MethodMessageHandlerTests { Map mappings = messageHandler.getHandlerMethods(); assertEquals(5, mappings.keySet().size()); - assertThat(mappings.keySet(), Matchers.containsInAnyOrder( + assertThat(mappings).containsOnlyKeys( "/handleMessage", "/handleMessageWithArgument", "/handleMessageWithError", - "/handleMessageMatch1", "/handleMessageMatch2")); + "/handleMessageMatch1", "/handleMessageMatch2"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesContextHolderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesContextHolderTests.java index 0abb7f23e5..6c31899caa 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesContextHolderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesContextHolderTests.java @@ -27,12 +27,13 @@ import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; + + + + + /** * Unit tests for @@ -61,27 +62,27 @@ public class SimpAttributesContextHolderTests { @Test public void resetAttributes() { SimpAttributesContextHolder.setAttributes(this.simpAttributes); - assertThat(SimpAttributesContextHolder.getAttributes(), sameInstance(this.simpAttributes)); + assertThat(SimpAttributesContextHolder.getAttributes()).isSameAs(this.simpAttributes); SimpAttributesContextHolder.resetAttributes(); - assertThat(SimpAttributesContextHolder.getAttributes(), nullValue()); + assertThat(SimpAttributesContextHolder.getAttributes()).isNull(); } @Test public void getAttributes() { - assertThat(SimpAttributesContextHolder.getAttributes(), nullValue()); + assertThat(SimpAttributesContextHolder.getAttributes()).isNull(); SimpAttributesContextHolder.setAttributes(this.simpAttributes); - assertThat(SimpAttributesContextHolder.getAttributes(), sameInstance(this.simpAttributes)); + assertThat(SimpAttributesContextHolder.getAttributes()).isSameAs(this.simpAttributes); } @Test public void setAttributes() { SimpAttributesContextHolder.setAttributes(this.simpAttributes); - assertThat(SimpAttributesContextHolder.getAttributes(), sameInstance(this.simpAttributes)); + assertThat(SimpAttributesContextHolder.getAttributes()).isSameAs(this.simpAttributes); SimpAttributesContextHolder.setAttributes(null); - assertThat(SimpAttributesContextHolder.getAttributes(), nullValue()); + assertThat(SimpAttributesContextHolder.getAttributes()).isNull(); } @Test @@ -98,11 +99,11 @@ public class SimpAttributesContextHolderTests { SimpAttributesContextHolder.setAttributesFromMessage(message); SimpAttributes attrs = SimpAttributesContextHolder.getAttributes(); - assertThat(attrs, notNullValue()); - assertThat(attrs.getSessionId(), is(sessionId)); + assertThat(attrs).isNotNull(); + assertThat(attrs.getSessionId()).isEqualTo(sessionId); attrs.setAttribute("name1", "value1"); - assertThat(map.get("name1"), is("value1")); + assertThat(map.get("name1")).isEqualTo("value1"); } @Test @@ -125,7 +126,7 @@ public class SimpAttributesContextHolderTests { @Test public void currentAttributes() { SimpAttributesContextHolder.setAttributes(this.simpAttributes); - assertThat(SimpAttributesContextHolder.currentAttributes(), sameInstance(this.simpAttributes)); + assertThat(SimpAttributesContextHolder.currentAttributes()).isSameAs(this.simpAttributes); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesTests.java index ab21e162a4..b51cf54e99 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesTests.java @@ -23,12 +23,8 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContainingInAnyOrder; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -57,8 +53,8 @@ public class SimpAttributesTests { public void getAttribute() { this.simpAttributes.setAttribute("name1", "value1"); - assertThat(this.simpAttributes.getAttribute("name1"), is("value1")); - assertThat(this.simpAttributes.getAttribute("name2"), nullValue()); + assertThat(this.simpAttributes.getAttribute("name1")).isEqualTo("value1"); + assertThat(this.simpAttributes.getAttribute("name2")).isNull(); } @Test @@ -67,7 +63,8 @@ public class SimpAttributesTests { this.simpAttributes.setAttribute("name2", "value1"); this.simpAttributes.setAttribute("name3", "value1"); - assertThat(this.simpAttributes.getAttributeNames(), arrayContainingInAnyOrder("name1", "name2", "name3")); + assertThat(this.simpAttributes.getAttributeNames()) + .containsExactlyInAnyOrder("name1", "name2", "name3"); } @Test @@ -76,7 +73,7 @@ public class SimpAttributesTests { this.simpAttributes.registerDestructionCallback("name1", callback); assertThat(this.simpAttributes.getAttribute( - SimpAttributes.DESTRUCTION_CALLBACK_NAME_PREFIX + "name1"), sameInstance(callback)); + SimpAttributes.DESTRUCTION_CALLBACK_NAME_PREFIX + "name1")).isSameAs(callback); } @Test @@ -94,12 +91,12 @@ public class SimpAttributesTests { this.simpAttributes.registerDestructionCallback("name1", callback1); this.simpAttributes.registerDestructionCallback("name2", callback2); - assertThat(this.simpAttributes.getAttributeNames().length, is(2)); + assertThat(this.simpAttributes.getAttributeNames().length).isEqualTo(2); } @Test public void getSessionMutex() { - assertThat(this.simpAttributes.getSessionMutex(), sameInstance(this.map)); + assertThat(this.simpAttributes.getSessionMutex()).isSameAs(this.map); } @Test @@ -107,7 +104,7 @@ public class SimpAttributesTests { Object mutex = new Object(); this.simpAttributes.setAttribute(SimpAttributes.SESSION_MUTEX_NAME, mutex); - assertThat(this.simpAttributes.getSessionMutex(), sameInstance(mutex)); + assertThat(this.simpAttributes.getSessionMutex()).isSameAs(mutex); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpSessionScopeTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpSessionScopeTests.java index fd2b3d2fdc..18c1253fe7 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpSessionScopeTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpSessionScopeTests.java @@ -25,9 +25,7 @@ import org.mockito.Mockito; import org.springframework.beans.factory.ObjectFactory; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -66,7 +64,7 @@ public class SimpSessionScopeTests { this.simpAttributes.setAttribute("name", "value"); Object actual = this.scope.get("name", this.objectFactory); - assertThat(actual, is("value")); + assertThat(actual).isEqualTo("value"); } @Test @@ -74,8 +72,8 @@ public class SimpSessionScopeTests { given(this.objectFactory.getObject()).willReturn("value"); Object actual = this.scope.get("name", this.objectFactory); - assertThat(actual, is("value")); - assertThat(this.simpAttributes.getAttribute("name"), is("value")); + assertThat(actual).isEqualTo("value"); + assertThat(this.simpAttributes.getAttribute("name")).isEqualTo("value"); } @Test @@ -83,11 +81,11 @@ public class SimpSessionScopeTests { this.simpAttributes.setAttribute("name", "value"); Object removed = this.scope.remove("name"); - assertThat(removed, is("value")); - assertThat(this.simpAttributes.getAttribute("name"), nullValue()); + assertThat(removed).isEqualTo("value"); + assertThat(this.simpAttributes.getAttribute("name")).isNull(); removed = this.scope.remove("name"); - assertThat(removed, nullValue()); + assertThat(removed).isNull(); } @Test @@ -101,7 +99,7 @@ public class SimpSessionScopeTests { @Test public void getSessionId() { - assertThat(this.scope.getConversationId(), is("session1")); + assertThat(this.scope.getConversationId()).isEqualTo("session1"); } 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 b5a15b0a71..cea060e088 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 @@ -67,8 +67,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -539,7 +538,7 @@ public class SimpAnnotationMethodMessageHandlerTests { @MessageMapping("/scope") public void scope() { SimpAttributes simpAttributes = SimpAttributesContextHolder.currentAttributes(); - assertThat(simpAttributes.getAttribute("name"), is("value")); + assertThat(simpAttributes.getAttribute("name")).isEqualTo("value"); this.method = "scope"; } 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 04116e42cb..56d6cd39d1 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 @@ -22,7 +22,6 @@ import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.context.ApplicationContext; @@ -77,7 +76,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; @@ -288,10 +287,10 @@ public class MessageBrokerConfigurationTests { CompositeMessageConverter compositeConverter = config.brokerMessageConverter(); List converters = compositeConverter.getConverters(); - assertThat(converters.size(), Matchers.is(3)); - assertThat(converters.get(0), Matchers.instanceOf(StringMessageConverter.class)); - assertThat(converters.get(1), Matchers.instanceOf(ByteArrayMessageConverter.class)); - assertThat(converters.get(2), Matchers.instanceOf(MappingJackson2MessageConverter.class)); + assertThat(converters).hasSize(3); + assertThat(converters.get(0)).isInstanceOf(StringMessageConverter.class); + assertThat(converters.get(1)).isInstanceOf(ByteArrayMessageConverter.class); + assertThat(converters.get(2)).isInstanceOf(MappingJackson2MessageConverter.class); ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver(); assertEquals(MimeTypeUtils.APPLICATION_JSON, ((DefaultContentTypeResolver) resolver).getDefaultMimeType()); @@ -328,9 +327,9 @@ public class MessageBrokerConfigurationTests { }; CompositeMessageConverter compositeConverter = config.brokerMessageConverter(); - assertThat(compositeConverter.getConverters().size(), Matchers.is(1)); + assertThat(compositeConverter.getConverters()).hasSize(1); Iterator iterator = compositeConverter.getConverters().iterator(); - assertThat(iterator.next(), Matchers.is(testConverter)); + assertThat(iterator.next()).isEqualTo(testConverter); } @Test @@ -346,12 +345,12 @@ public class MessageBrokerConfigurationTests { }; CompositeMessageConverter compositeConverter = config.brokerMessageConverter(); - assertThat(compositeConverter.getConverters().size(), Matchers.is(4)); + assertThat(compositeConverter.getConverters()).hasSize(4); Iterator iterator = compositeConverter.getConverters().iterator(); - assertThat(iterator.next(), Matchers.is(testConverter)); - assertThat(iterator.next(), Matchers.instanceOf(StringMessageConverter.class)); - assertThat(iterator.next(), Matchers.instanceOf(ByteArrayMessageConverter.class)); - assertThat(iterator.next(), Matchers.instanceOf(MappingJackson2MessageConverter.class)); + assertThat(iterator.next()).isEqualTo(testConverter); + assertThat(iterator.next()).isInstanceOf(StringMessageConverter.class); + assertThat(iterator.next()).isInstanceOf(ByteArrayMessageConverter.class); + assertThat(iterator.next()).isInstanceOf(MappingJackson2MessageConverter.class); } @Test @@ -375,8 +374,8 @@ public class MessageBrokerConfigurationTests { AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {}; config.setApplicationContext(new StaticApplicationContext()); - assertThat(config.simpValidator(), Matchers.notNullValue()); - assertThat(config.simpValidator(), Matchers.instanceOf(OptionalValidatorFactoryBean.class)); + assertThat(config.simpValidator()).isNotNull(); + assertThat(config.simpValidator()).isInstanceOf(OptionalValidatorFactoryBean.class); } @Test @@ -399,8 +398,8 @@ public class MessageBrokerConfigurationTests { AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {}; config.setApplicationContext(appCxt); - assertThat(config.simpValidator(), Matchers.notNullValue()); - assertThat(config.simpValidator(), Matchers.instanceOf(TestValidator.class)); + assertThat(config.simpValidator()).isNotNull(); + assertThat(config.simpValidator()).isInstanceOf(TestValidator.class); } @Test @@ -410,7 +409,7 @@ public class MessageBrokerConfigurationTests { SimpAnnotationMethodMessageHandler messageHandler = context.getBean(SimpAnnotationMethodMessageHandler.class); - assertThat(messageHandler.getValidator(), Matchers.notNullValue(Validator.class)); + assertThat(messageHandler.getValidator()).isNotNull(); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java index 6f4978e782..893c845f4a 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 @@ -43,9 +43,8 @@ import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import org.springframework.util.concurrent.SettableListenableFuture; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -111,7 +110,7 @@ public class DefaultStompSessionTests { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); assertEquals(StompCommand.CONNECT, accessor.getCommand()); assertEquals("my-host", accessor.getHost()); - assertThat(accessor.getAcceptVersion(), containsInAnyOrder("1.1", "1.2")); + assertThat(accessor.getAcceptVersion()).containsExactly("1.1", "1.2"); assertArrayEquals(new long[] {11, 12}, accessor.getHeartbeat()); } @@ -125,7 +124,7 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); assertEquals(StompCommand.CONNECT, accessor.getCommand()); - assertThat(accessor.getAcceptVersion(), containsInAnyOrder("1.1")); + assertThat(accessor.getAcceptVersion()).containsExactly("1.1"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java index acedb48cf1..4e06b868ee 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java @@ -40,8 +40,7 @@ import org.springframework.util.Assert; import org.springframework.util.SocketUtils; import org.springframework.util.concurrent.ListenableFuture; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -120,10 +119,10 @@ public class ReactorNettyTcpStompClientTests { ListenableFuture producerFuture = this.client.connect(producingHandler); assertTrue(consumingHandler1.awaitForMessageCount(2, 5000)); - assertThat(consumingHandler1.getReceived(), containsInAnyOrder("foo1", "foo2")); + assertThat(consumingHandler1.getReceived()).containsExactly("foo1", "foo2"); assertTrue(consumingHandler2.awaitForMessageCount(2, 5000)); - assertThat(consumingHandler2.getReceived(), containsInAnyOrder("foo1", "foo2")); + assertThat(consumingHandler2.getReceived()).containsExactly("foo1", "foo2"); consumerFuture1.get().disconnect(); consumerFuture2.get().disconnect(); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java index 9810e6722a..b3133c1ee7 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java @@ -21,7 +21,6 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; -import org.hamcrest.CoreMatchers; import org.junit.Test; import org.springframework.messaging.Message; @@ -37,7 +36,7 @@ import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import org.springframework.util.MultiValueMap; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -113,7 +112,7 @@ public class StompHeaderAccessorTests { assertNotNull(headerAccessor.getHeader("stompCredentials")); assertEquals("joe", headerAccessor.getLogin()); assertEquals("joe123", headerAccessor.getPasscode()); - assertThat(headerAccessor.toString(), CoreMatchers.containsString("passcode=[PROTECTED]")); + assertThat(headerAccessor.toString()).contains("passcode=[PROTECTED]"); Map> output = headerAccessor.toNativeHeaderMap(); assertEquals("joe", output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0)); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java index 91007ee551..c38aeca2a2 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java @@ -30,8 +30,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.converter.MappingJackson2MessageConverter; import org.springframework.messaging.converter.MessageConverter; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -162,13 +161,13 @@ public class MultiServerUserRegistryTests { SimpUser user = this.registry.getUsers().iterator().next(); assertTrue(user.hasSessions()); assertEquals(2, user.getSessions().size()); - assertThat(user.getSessions(), containsInAnyOrder(localSession, remoteSession)); + assertThat(user.getSessions()).containsExactlyInAnyOrder(localSession, remoteSession); assertSame(localSession, user.getSession("sess123")); assertEquals(remoteSession, user.getSession("sess456")); user = this.registry.getUser("joe"); assertEquals(2, user.getSessions().size()); - assertThat(user.getSessions(), containsInAnyOrder(localSession, remoteSession)); + assertThat(user.getSessions()).containsExactlyInAnyOrder(localSession, remoteSession); assertSame(localSession, user.getSession("sess123")); assertEquals(remoteSession, user.getSession("sess456")); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java index bc05885cc1..33f19f9237 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java @@ -18,9 +18,8 @@ package org.springframework.messaging.support; import org.junit.Test; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Gary Russell @@ -32,12 +31,12 @@ public class ErrorMessageTests { public void testToString() { ErrorMessage em = new ErrorMessage(new RuntimeException("foo")); String emString = em.toString(); - assertThat(emString, not(containsString("original"))); + assertThat(emString).doesNotContain("original"); em = new ErrorMessage(new RuntimeException("foo"), new GenericMessage<>("bar")); emString = em.toString(); - assertThat(emString, containsString("original")); - assertThat(emString, containsString(em.getOriginalMessage().toString())); + assertThat(emString).contains("original"); + assertThat(emString).contains(em.getOriginalMessage().toString()); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java index 4b23d420f0..02a0f29683 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java @@ -31,9 +31,8 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -108,8 +107,8 @@ public class ExecutorSubscribableChannelTests { @Test public void subscribeTwice() { - assertThat(this.channel.subscribe(this.handler), equalTo(true)); - assertThat(this.channel.subscribe(this.handler), equalTo(false)); + assertThat(this.channel.subscribe(this.handler)).isEqualTo(true); + assertThat(this.channel.subscribe(this.handler)).isEqualTo(false); this.channel.send(this.message); verify(this.handler, times(1)).handleMessage(this.message); } @@ -117,8 +116,8 @@ public class ExecutorSubscribableChannelTests { @Test public void unsubscribeTwice() { this.channel.subscribe(this.handler); - assertThat(this.channel.unsubscribe(this.handler), equalTo(true)); - assertThat(this.channel.unsubscribe(this.handler), equalTo(false)); + assertThat(this.channel.unsubscribe(this.handler)).isEqualTo(true); + assertThat(this.channel.unsubscribe(this.handler)).isEqualTo(false); this.channel.send(this.message); verify(this.handler, never()).handleMessage(this.message); } @@ -134,7 +133,7 @@ public class ExecutorSubscribableChannelTests { this.channel.send(message); } catch (MessageDeliveryException actualException) { - assertThat(actualException.getCause(), equalTo(ex)); + assertThat(actualException.getCause()).isEqualTo(ex); } verifyZeroInteractions(secondHandler); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java index cfe07607c4..b0dd544018 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java @@ -29,9 +29,8 @@ import org.springframework.messaging.MessageHeaders; import org.springframework.util.MimeTypeUtils; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -344,7 +343,7 @@ public class MessageHeaderAccessorTests { return payload; } }); - assertThat(actual, startsWith("headers={contentType=text/plain} payload=" + getClass().getName() + "$")); + assertThat(actual).startsWith("headers={contentType=text/plain} payload=" + getClass().getName() + "$"); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java index 88097bfa0b..ec1fbabfe0 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java @@ -27,11 +27,9 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; @@ -54,7 +52,7 @@ public class SharedEntityManagerCreatorTests { EntityManagerFactory emf = mock(EntityManagerFactory.class, withSettings().extraInterfaces(EntityManagerFactoryInfo.class)); // EntityManagerFactoryInfo.getEntityManagerInterface returns null - assertThat(SharedEntityManagerCreator.createSharedEntityManager(emf), is(notNullValue())); + assertThat(SharedEntityManagerCreator.createSharedEntityManager(emf)).isNotNull(); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManagerTests.java index a0e7f622a4..338fad786c 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManagerTests.java @@ -23,8 +23,9 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.orm.jpa.domain.Person; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.assertj.core.api.Assertions.assertThat; + + /** * Tests for {@link DefaultPersistenceUnitManager}. @@ -54,9 +55,9 @@ public class DefaultPersistenceUnitManagerTests { private void testDefaultDomain() { SpringPersistenceUnitInfo puInfo = buildDefaultPersistenceUnitInfo(); - assertThat(puInfo.getManagedClassNames(), containsInAnyOrder( + assertThat(puInfo.getManagedClassNames()).contains( "org.springframework.orm.jpa.domain.Person", - "org.springframework.orm.jpa.domain.DriversLicense")); + "org.springframework.orm.jpa.domain.DriversLicense"); } private SpringPersistenceUnitInfo buildDefaultPersistenceUnitInfo() { diff --git a/spring-oxm/spring-oxm.gradle b/spring-oxm/spring-oxm.gradle index 153c4f4417..a05c2360cf 100644 --- a/spring-oxm/spring-oxm.gradle +++ b/spring-oxm/spring-oxm.gradle @@ -71,6 +71,7 @@ dependencies { } testCompile(files(genJaxb.classesDir).builtBy(genJaxb)) testCompile("org.xmlunit:xmlunit-matchers:2.6.2") + testCompile("org.xmlunit:xmlunit-assertj:2.6.2") testRuntime("com.sun.xml.bind:jaxb-core:2.3.0.1") testRuntime("com.sun.xml.bind:jaxb-impl:2.3.0.1") } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java index ee48b70bf3..b956a3f6f9 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java @@ -34,11 +34,11 @@ import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; -import org.xmlunit.matchers.CompareMatcher; +import org.springframework.tests.XmlContent; import org.springframework.util.xml.StaxUtils; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -85,7 +85,7 @@ public abstract class AbstractMarshallerTests { flightElement.appendChild(numberElement); Text text = expected.createTextNode("42"); numberElement.appendChild(text); - assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).isSimilarToIgnoringWhitespace(expected); } @Test @@ -109,7 +109,7 @@ public abstract class AbstractMarshallerTests { flightElement.appendChild(numberElement); Text text = expected.createTextNode("42"); numberElement.appendChild(text); - assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected)); + assertThat(XmlContent.of(result)).isSimilarToIgnoringWhitespace(expected); } @Test @@ -117,7 +117,7 @@ public abstract class AbstractMarshallerTests { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); marshaller.marshal(flights, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.of(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING); } @Test @@ -125,8 +125,7 @@ public abstract class AbstractMarshallerTests { ByteArrayOutputStream os = new ByteArrayOutputStream(); StreamResult result = new StreamResult(os); marshaller.marshal(flights, result); - assertThat("Marshaller writes invalid StreamResult", new String(os.toByteArray(), "UTF-8"), - isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.of(new String(os.toByteArray(), "UTF-8"))).isSimilarToIgnoringWhitespace(EXPECTED_STRING); } @Test @@ -136,7 +135,7 @@ public abstract class AbstractMarshallerTests { XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer); Result result = StaxUtils.createStaxResult(streamWriter); marshaller.marshal(flights, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING); } @Test @@ -146,7 +145,7 @@ public abstract class AbstractMarshallerTests { XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer); Result result = StaxUtils.createStaxResult(eventWriter); marshaller.marshal(flights, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING); } @Test @@ -156,7 +155,7 @@ public abstract class AbstractMarshallerTests { XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer); StAXResult result = new StAXResult(streamWriter); marshaller.marshal(flights, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING); } @Test @@ -166,11 +165,6 @@ public abstract class AbstractMarshallerTests { XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer); StAXResult result = new StAXResult(eventWriter); marshaller.marshal(flights, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); - } - - private static CompareMatcher isSimilarTo(final Object content) { - return CompareMatcher.isSimilarTo(content) - .ignoreWhitespace(); + assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING); } } 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 95dea03b6e..2d3782d12d 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 @@ -52,12 +52,13 @@ import org.springframework.oxm.jaxb.test.FlightType; import org.springframework.oxm.jaxb.test.Flights; import org.springframework.oxm.jaxb.test.ObjectFactory; import org.springframework.oxm.mime.MimeContainer; +import org.springframework.tests.XmlContent; import org.springframework.util.FileCopyUtils; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -73,7 +74,6 @@ import static org.xmlunit.diff.ComparisonType.XML_STANDALONE; import static org.xmlunit.diff.DifferenceEvaluators.Default; import static org.xmlunit.diff.DifferenceEvaluators.chain; import static org.xmlunit.diff.DifferenceEvaluators.downgradeDifferencesToEqual; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -135,8 +135,7 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTeststest").withDifferenceEvaluator(ev)); + assertThat(XmlContent.from(writer)).isSimilarTo("test", ev); } @Test // SPR-10806 diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java index 7ff57ec49c..356c3824a4 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java @@ -23,13 +23,13 @@ import org.junit.BeforeClass; import org.junit.Test; import org.springframework.oxm.AbstractMarshallerTests; +import org.springframework.tests.XmlContent; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * NOTE: These tests fail under Eclipse/IDEA because JiBX binding does not occur by @@ -81,7 +81,7 @@ public class JibxMarshallerTests extends AbstractMarshallerTests String expected = "\n" + "\n" + " \n" + " 42\n" + " \n" + ""; - assertThat(writer.toString(), isSimilarTo(expected).ignoreWhitespace()); + assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(expected); } @Test 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 91f45bfafe..977001a6d3 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 @@ -56,9 +56,10 @@ import org.xml.sax.ContentHandler; import org.xmlunit.builder.Input; import org.xmlunit.xpath.JAXPXPathEngine; +import org.springframework.tests.XmlContent; import org.springframework.util.xml.StaxUtils; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -66,7 +67,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -106,7 +106,7 @@ public class XStreamMarshallerTests { flightElement.appendChild(numberElement); Text text = expected.createTextNode("42"); numberElement.appendChild(text); - assertThat("Marshaller writes invalid DOMResult", document, isSimilarTo(expected)); + assertThat(XmlContent.of(document)).isSimilarTo(expected); } // see SWS-392 @@ -135,7 +135,7 @@ public class XStreamMarshallerTests { eFlightElement.appendChild(eNumberElement); Text text = expected.createTextNode("42"); eNumberElement.appendChild(text); - assertThat("Marshaller writes invalid DOMResult", existent, isSimilarTo(expected)); + assertThat(XmlContent.of(existent)).isSimilarTo(expected); } @Test @@ -143,7 +143,7 @@ public class XStreamMarshallerTests { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); marshaller.marshal(flight, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING); } @Test @@ -152,7 +152,7 @@ public class XStreamMarshallerTests { StreamResult result = new StreamResult(os); marshaller.marshal(flight, result); String s = new String(os.toByteArray(), "UTF-8"); - assertThat("Marshaller writes invalid StreamResult", s, isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.of(s)).isSimilarTo(EXPECTED_STRING); } @Test @@ -177,7 +177,7 @@ public class XStreamMarshallerTests { XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer); Result result = StaxUtils.createStaxResult(streamWriter); marshaller.marshal(flight, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING); } @Test @@ -187,7 +187,7 @@ public class XStreamMarshallerTests { XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer); Result result = StaxUtils.createStaxResult(eventWriter); marshaller.marshal(flight, result); - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING); } @Test @@ -196,7 +196,7 @@ public class XStreamMarshallerTests { byte[] buf = new byte[]{0x1, 0x2}; Writer writer = new StringWriter(); marshaller.marshal(buf, new StreamResult(writer)); - assertThat(writer.toString(), isSimilarTo("AQI=")); + assertThat(XmlContent.from(writer)).isSimilarTo("AQI="); Reader reader = new StringReader(writer.toString()); byte[] bufResult = (byte[]) marshaller.unmarshal(new StreamSource(reader)); assertTrue("Invalid result", Arrays.equals(buf, bufResult)); @@ -208,7 +208,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); String expected = ""; - assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(expected)); + assertThat(XmlContent.from(writer)).isSimilarTo(expected); } @Test @@ -217,7 +217,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); String expected = ""; - assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(expected)); + assertThat(XmlContent.from(writer)).isSimilarTo(expected); } @Test @@ -226,7 +226,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); String expected = ""; - assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(expected)); + assertThat(XmlContent.from(writer)).isSimilarTo(expected); } @Test @@ -235,7 +235,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); String expected = ""; - assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(expected)); + assertThat(XmlContent.from(writer)).isSimilarTo(expected); } @Test @@ -249,7 +249,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); - assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING); } @Test @@ -263,7 +263,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); - assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(EXPECTED_STRING)); + assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING); } @Test @@ -272,7 +272,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); String expected = "42"; - assertThat("Marshaller does not use aliases", writer.toString(), isSimilarTo(expected)); + assertThat(XmlContent.from(writer)).isSimilarTo(expected); } @Test @@ -347,7 +347,7 @@ public class XStreamMarshallerTests { flight.setFlightNumber(42); marshaller.marshal(flight, result); String expected = "42"; - assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(expected)); + assertThat(XmlContent.from(writer)).isSimilarTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java index 8cbda1dd84..9fc2a953f5 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java @@ -28,10 +28,9 @@ import javax.servlet.ServletResponse; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -84,8 +83,8 @@ public class MockFilterChainTests { MockFilterChain chain = new MockFilterChain(); chain.doFilter(this.request, this.response); - assertThat(chain.getRequest(), is(request)); - assertThat(chain.getResponse(), is(response)); + assertThat(chain.getRequest()).isEqualTo(request); + assertThat(chain.getResponse()).isEqualTo(response); assertThatIllegalStateException().isThrownBy(() -> chain.doFilter(this.request, this.response)) diff --git a/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java index 3c2c48f080..a2acde1250 100644 --- a/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java @@ -34,9 +34,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.HierarchyMode; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -95,21 +93,21 @@ public class ContextHierarchyDirtiesContextTests { Result result = jUnitCore.run(testClass); assertTrue("all tests passed", result.wasSuccessful()); - assertThat(ContextHierarchyDirtiesContextTests.context, notNullValue()); + assertThat(ContextHierarchyDirtiesContextTests.context).isNotNull(); ConfigurableApplicationContext bazContext = (ConfigurableApplicationContext) ContextHierarchyDirtiesContextTests.context; assertEquals("baz", ContextHierarchyDirtiesContextTests.baz); - assertThat("bazContext#isActive()", bazContext.isActive(), is(isBazContextActive)); + assertThat(bazContext.isActive()).isEqualTo(isBazContextActive); ConfigurableApplicationContext barContext = (ConfigurableApplicationContext) bazContext.getParent(); - assertThat(barContext, notNullValue()); + assertThat(barContext).isNotNull(); assertEquals("bar", ContextHierarchyDirtiesContextTests.bar); - assertThat("barContext#isActive()", barContext.isActive(), is(isBarContextActive)); + assertThat(barContext.isActive()).isEqualTo(isBarContextActive); ConfigurableApplicationContext fooContext = (ConfigurableApplicationContext) barContext.getParent(); - assertThat(fooContext, notNullValue()); + assertThat(fooContext).isNotNull(); assertEquals("foo", ContextHierarchyDirtiesContextTests.foo); - assertThat("fooContext#isActive()", fooContext.isActive(), is(isFooContextActive)); + assertThat(fooContext.isActive()).isEqualTo(isFooContextActive); } diff --git a/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java b/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java index 5d37e85a17..39f507c336 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java @@ -26,8 +26,7 @@ import org.junit.Test; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toCollection; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -76,7 +75,7 @@ public class TestContextConcurrencyTests { throw new RuntimeException(ex); } }); - assertThat(actualMethods, equalTo(expectedMethods)); + assertThat(actualMethods).isEqualTo(expectedMethods); }); assertEquals(0, tcm.getTestContext().attributeNames().length); } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/TestPropertySourceInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/TestPropertySourceInterfaceTests.java index a8112da8c8..ad3d18dcde 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/TestPropertySourceInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/TestPropertySourceInterfaceTests.java @@ -24,8 +24,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Sam Brannen @@ -40,8 +40,8 @@ public class TestPropertySourceInterfaceTests implements TestPropertySourceTestI @Test public void propertiesAreAvailableInEnvironment() { - assertThat(property("foo"), is("bar")); - assertThat(property("enigma"), is("42")); + assertThat(property("foo")).isEqualTo("bar"); + assertThat(property("enigma")).isEqualTo("42"); } private String property(String key) { diff --git a/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java index 5cfd3f1530..f36150344b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.springframework.test.context.support.TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME; @@ -56,16 +55,16 @@ public class InlinedPropertiesTestPropertySourceTests { @Test public void propertiesAreAvailableInEnvironment() { // Simple key/value pairs - assertThat(property("foo"), is("bar")); - assertThat(property("baz"), is("quux")); - assertThat(property("enigma"), is("42")); + assertThat(property("foo")).isEqualTo("bar"); + assertThat(property("baz")).isEqualTo("quux"); + assertThat(property("enigma")).isEqualTo("42"); // Values containing key/value delimiters (":", "=", " ") - assertThat(property("x.y.z"), is("a=b=c")); - assertThat(property("server.url"), is("https://example.com")); - assertThat(property("key.value.1"), is("key=value")); - assertThat(property("key.value.2"), is("key=value")); - assertThat(property("key.value.3"), is("key:value")); + assertThat(property("x.y.z")).isEqualTo("a=b=c"); + assertThat(property("server.url")).isEqualTo("https://example.com"); + assertThat(property("key.value.1")).isEqualTo("key=value"); + assertThat(property("key.value.2")).isEqualTo("key=value"); + assertThat(property("key.value.3")).isEqualTo("key:value"); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java index 3597e0fa62..0207da6892 100644 --- a/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java @@ -51,10 +51,8 @@ import org.springframework.util.ReflectionUtils; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.only; @@ -147,11 +145,11 @@ public class EventPublishingTestExecutionListenerIntegrationTests { testContextManager.beforeTestMethod(testInstance, method); - assertThat(countDownLatch.await(2, TimeUnit.SECONDS), equalTo(true)); + assertThat(countDownLatch.await(2, TimeUnit.SECONDS)).isEqualTo(true); verify(listener, only()).beforeTestMethod(testContext); - assertThat(TrackingAsyncUncaughtExceptionHandler.asyncException.getMessage(), - startsWith("Asynchronous exception for test method [" + methodName + "] in thread [" + THREAD_NAME_PREFIX)); + assertThat(TrackingAsyncUncaughtExceptionHandler.asyncException.getMessage()) + .startsWith("Asynchronous exception for test method [" + methodName + "] in thread [" + THREAD_NAME_PREFIX); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerTests.java b/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerTests.java index 02839a81e3..e05fff03fb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerTests.java @@ -33,9 +33,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.test.context.TestContext; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willCallRealMethod; @@ -158,8 +156,8 @@ public class EventPublishingTestExecutionListenerTests { // Verify the type of event that was published. ApplicationEvent event = eventFactory.getValue().apply(testContext); - assertThat(event, instanceOf(eventClass)); - assertThat(event.getSource(), equalTo(testContext)); + assertThat(event).isInstanceOf(eventClass); + assertThat(event.getSource()).isEqualTo(testContext); } private void assertNoEvent(Class eventClass, Consumer callback) { @@ -175,8 +173,8 @@ public class EventPublishingTestExecutionListenerTests { // In any case, we can still verify the type of event that would have // been published. ApplicationEvent event = eventFactory.getValue().apply(testContext); - assertThat(event, instanceOf(eventClass)); - assertThat(event.getSource(), equalTo(testContext)); + assertThat(event).isInstanceOf(eventClass); + assertThat(event.getSource()).isEqualTo(testContext); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfConditionTests.java b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfConditionTests.java index b932d1d946..c9b5e41ce0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfConditionTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfConditionTests.java @@ -19,7 +19,6 @@ package org.springframework.test.context.junit.jupiter; import java.lang.reflect.Method; import java.util.Optional; -import org.hamcrest.Matcher; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ConditionEvaluationResult; import org.junit.jupiter.api.extension.ExtensionContext; @@ -30,16 +29,9 @@ import org.springframework.test.context.TestContextManager; import org.springframework.test.context.junit.SpringJUnitJupiterTestSuite; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.endsWith; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -63,8 +55,9 @@ class DisabledIfConditionTests { @Test void missingDisabledIf() { - assertResult(condition.evaluateExecutionCondition(buildExtensionContext("missingDisabledIf")), false, - endsWith("missingDisabledIf() is enabled since @DisabledIf is not present")); + ConditionEvaluationResult result = condition.evaluateExecutionCondition(buildExtensionContext("missingDisabledIf")); + assertThat(result.isDisabled()).isFalse(); + assertThat(result.getReason().get()).endsWith("missingDisabledIf() is enabled since @DisabledIf is not present"); } @Test @@ -85,8 +78,7 @@ class DisabledIfConditionTests { Method method = ReflectionUtils.findMethod(getClass(), methodName); - assertThat(exception.getMessage(), - is(equalTo("@DisabledIf(\"#{6 * 7}\") on " + method + " must evaluate to a String or a Boolean, not java.lang.Integer"))); + assertThat(exception).hasMessage("@DisabledIf(\"#{6 * 7}\") on " + method + " must evaluate to a String or a Boolean, not java.lang.Integer"); } @Test @@ -97,25 +89,28 @@ class DisabledIfConditionTests { Method method = ReflectionUtils.findMethod(getClass(), methodName); - assertThat(exception.getMessage(), - is(equalTo("@DisabledIf(\"#{'enigma'}\") on " + method + " must evaluate to \"true\" or \"false\", not \"enigma\""))); + assertThat(exception).hasMessage("@DisabledIf(\"#{'enigma'}\") on " + method + " must evaluate to \"true\" or \"false\", not \"enigma\""); } @Test void disabledWithCustomReason() { - assertResult(condition.evaluateExecutionCondition(buildExtensionContext("customReason")), true, is(equalTo("Because... 42!"))); + ConditionEvaluationResult result = condition.evaluateExecutionCondition(buildExtensionContext("customReason")); + assertThat(result.isDisabled()).isTrue(); + assertThat(result.getReason()).contains("Because... 42!"); } @Test void disabledWithDefaultReason() { - assertResult(condition.evaluateExecutionCondition(buildExtensionContext("defaultReason")), true, - endsWith("defaultReason() is disabled because @DisabledIf(\"#{1 + 1 eq 2}\") evaluated to true")); + ConditionEvaluationResult result = condition.evaluateExecutionCondition(buildExtensionContext("defaultReason")); + assertThat(result.isDisabled()).isTrue(); + assertThat(result.getReason().get()).endsWith("defaultReason() is disabled because @DisabledIf(\"#{1 + 1 eq 2}\") evaluated to true"); } @Test void notDisabledWithDefaultReason() { - assertResult(condition.evaluateExecutionCondition(buildExtensionContext("neverDisabledWithDefaultReason")), false, endsWith( - "neverDisabledWithDefaultReason() is enabled because @DisabledIf(\"false\") did not evaluate to true")); + ConditionEvaluationResult result = condition.evaluateExecutionCondition(buildExtensionContext("neverDisabledWithDefaultReason")); + assertThat(result.isDisabled()).isFalse(); + assertThat(result.getReason().get()).endsWith("neverDisabledWithDefaultReason() is enabled because @DisabledIf(\"false\") did not evaluate to true"); } // ------------------------------------------------------------------------- @@ -137,22 +132,7 @@ class DisabledIfConditionTests { IllegalStateException exception = assertThrows(IllegalStateException.class, () -> condition.evaluateExecutionCondition(buildExtensionContext(methodName))); - assertThat(exception.getMessage(), containsString("must not be blank")); - } - - private void assertResult(ConditionEvaluationResult result, boolean disabled, Matcher matcher) { - assertNotNull(result); - - if (disabled) { - assertTrue(result.isDisabled()); - } - else { - assertFalse(result.isDisabled()); - } - - Optional reason = result.getReason(); - assertTrue(reason.isPresent()); - assertThat(reason.get(), matcher); + assertThat(exception.getMessage()).contains("must not be blank"); } // ------------------------------------------------------------------------- diff --git a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/MultipleWebRequestsSpringExtensionTests.java b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/MultipleWebRequestsSpringExtensionTests.java index f6be98e30c..b12292b099 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/MultipleWebRequestsSpringExtensionTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/MultipleWebRequestsSpringExtensionTests.java @@ -25,7 +25,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; -import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.is; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/WebSpringExtensionTests.java b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/WebSpringExtensionTests.java index 67ca2ebd45..f07ca2fc5f 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/WebSpringExtensionTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/web/WebSpringExtensionTests.java @@ -25,7 +25,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; -import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr6128/AutowiredQualifierTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr6128/AutowiredQualifierTests.java index cf03e96dc2..8436a50c95 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr6128/AutowiredQualifierTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr6128/AutowiredQualifierTests.java @@ -24,8 +24,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests to verify claims made in configAttributesListClassLevel1 = hierarchyAttributes.get(0); debugConfigAttributes(configAttributesListClassLevel1); assertEquals(1, configAttributesListClassLevel1.size()); - assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("one.xml")); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("one.xml"); List configAttributesListClassLevel2 = hierarchyAttributes.get(1); debugConfigAttributes(configAttributesListClassLevel2); @@ -138,7 +135,7 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf List configAttributesListClassLevel3 = hierarchyAttributes.get(2); debugConfigAttributes(configAttributesListClassLevel3); assertEquals(1, configAttributesListClassLevel3.size()); - assertThat(configAttributesListClassLevel3.get(0).getLocations()[0], equalTo("three.xml")); + assertThat(configAttributesListClassLevel3.get(0).getLocations()[0]).isEqualTo("three.xml"); } @Test @@ -149,7 +146,7 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf List configAttributesListClassLevel1 = hierarchyAttributes.get(0); debugConfigAttributes(configAttributesListClassLevel1); assertEquals(1, configAttributesListClassLevel1.size()); - assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("A.xml")); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("A.xml"); assertAttributes(configAttributesListClassLevel1.get(0), TestClass1WithSingleLevelContextHierarchyFromMetaAnnotation.class, new String[] { "A.xml" }, EMPTY_CLASS_ARRAY, ContextLoader.class, true); @@ -167,7 +164,7 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf List configAttributesListClassLevel3 = hierarchyAttributes.get(2); debugConfigAttributes(configAttributesListClassLevel3); assertEquals(1, configAttributesListClassLevel3.size()); - assertThat(configAttributesListClassLevel3.get(0).getLocations()[0], equalTo("C.xml")); + assertThat(configAttributesListClassLevel3.get(0).getLocations()[0]).isEqualTo("C.xml"); assertAttributes(configAttributesListClassLevel3.get(0), TestClass3WithSingleLevelContextHierarchyFromMetaAnnotation.class, new String[] { "C.xml" }, EMPTY_CLASS_ARRAY, ContextLoader.class, true); @@ -182,10 +179,10 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf debugConfigAttributes(configAttributesListClassLevel2); assertEquals(1, configAttributesListClassLevel1.size()); - assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("one.xml")); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("one.xml"); assertEquals(1, configAttributesListClassLevel2.size()); - assertThat(configAttributesListClassLevel2.get(0).getLocations()[0], equalTo("two.xml")); + assertThat(configAttributesListClassLevel2.get(0).getLocations()[0]).isEqualTo("two.xml"); } @Test @@ -216,45 +213,44 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf List configAttributesListClassLevel1 = hierarchyAttributes.get(0); debugConfigAttributes(configAttributesListClassLevel1); assertEquals(2, configAttributesListClassLevel1.size()); - assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("1-A.xml")); - assertThat(configAttributesListClassLevel1.get(1).getLocations()[0], equalTo("1-B.xml")); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("1-A.xml"); + assertThat(configAttributesListClassLevel1.get(1).getLocations()[0]).isEqualTo("1-B.xml"); List configAttributesListClassLevel2 = hierarchyAttributes.get(1); debugConfigAttributes(configAttributesListClassLevel2); assertEquals(2, configAttributesListClassLevel2.size()); - assertThat(configAttributesListClassLevel2.get(0).getLocations()[0], equalTo("2-A.xml")); - assertThat(configAttributesListClassLevel2.get(1).getLocations()[0], equalTo("2-B.xml")); + assertThat(configAttributesListClassLevel2.get(0).getLocations()[0]).isEqualTo("2-A.xml"); + assertThat(configAttributesListClassLevel2.get(1).getLocations()[0]).isEqualTo("2-B.xml"); List configAttributesListClassLevel3 = hierarchyAttributes.get(2); debugConfigAttributes(configAttributesListClassLevel3); assertEquals(3, configAttributesListClassLevel3.size()); - assertThat(configAttributesListClassLevel3.get(0).getLocations()[0], equalTo("3-A.xml")); - assertThat(configAttributesListClassLevel3.get(1).getLocations()[0], equalTo("3-B.xml")); - assertThat(configAttributesListClassLevel3.get(2).getLocations()[0], equalTo("3-C.xml")); + assertThat(configAttributesListClassLevel3.get(0).getLocations()[0]).isEqualTo("3-A.xml"); + assertThat(configAttributesListClassLevel3.get(1).getLocations()[0]).isEqualTo("3-B.xml"); + assertThat(configAttributesListClassLevel3.get(2).getLocations()[0]).isEqualTo("3-C.xml"); } @Test public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchies() { Map> map = buildContextHierarchyMap(TestClass3WithMultiLevelContextHierarchy.class); - assertThat(map.size(), is(3)); - assertThat(map.keySet(), hasItems("alpha", "beta", "gamma")); + assertThat(map).hasSize(3).containsKeys("alpha", "beta", "gamma"); List alphaConfig = map.get("alpha"); - assertThat(alphaConfig.size(), is(3)); - assertThat(alphaConfig.get(0).getLocations()[0], is("1-A.xml")); - assertThat(alphaConfig.get(1).getLocations()[0], is("2-A.xml")); - assertThat(alphaConfig.get(2).getLocations()[0], is("3-A.xml")); + assertThat(alphaConfig).hasSize(3); + assertThat(alphaConfig.get(0).getLocations()[0]).isEqualTo("1-A.xml"); + assertThat(alphaConfig.get(1).getLocations()[0]).isEqualTo("2-A.xml"); + assertThat(alphaConfig.get(2).getLocations()[0]).isEqualTo("3-A.xml"); List betaConfig = map.get("beta"); - assertThat(betaConfig.size(), is(3)); - assertThat(betaConfig.get(0).getLocations()[0], is("1-B.xml")); - assertThat(betaConfig.get(1).getLocations()[0], is("2-B.xml")); - assertThat(betaConfig.get(2).getLocations()[0], is("3-B.xml")); + assertThat(betaConfig).hasSize(3); + assertThat(betaConfig.get(0).getLocations()[0]).isEqualTo("1-B.xml"); + assertThat(betaConfig.get(1).getLocations()[0]).isEqualTo("2-B.xml"); + assertThat(betaConfig.get(2).getLocations()[0]).isEqualTo("3-B.xml"); List gammaConfig = map.get("gamma"); - assertThat(gammaConfig.size(), is(1)); - assertThat(gammaConfig.get(0).getLocations()[0], is("3-C.xml")); + assertThat(gammaConfig).hasSize(1); + assertThat(gammaConfig.get(0).getLocations()[0]).isEqualTo("3-C.xml"); } @Test @@ -269,26 +265,25 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf String level6 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 6; String level7 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 7; - assertThat(map.size(), is(7)); - assertThat(map.keySet(), hasItems(level1, level2, level3, level4, level5, level6, level7)); + assertThat(map).hasSize(7).containsKeys(level1, level2, level3, level4, level5, level6, level7); List level1Config = map.get(level1); - assertThat(level1Config.size(), is(1)); - assertThat(level1Config.get(0).getLocations()[0], is("1-A.xml")); + assertThat(level1Config).hasSize(1); + assertThat(level1Config.get(0).getLocations()[0]).isEqualTo("1-A.xml"); List level2Config = map.get(level2); - assertThat(level2Config.size(), is(1)); - assertThat(level2Config.get(0).getLocations()[0], is("1-B.xml")); + assertThat(level2Config).hasSize(1); + assertThat(level2Config.get(0).getLocations()[0]).isEqualTo("1-B.xml"); List level3Config = map.get(level3); - assertThat(level3Config.size(), is(1)); - assertThat(level3Config.get(0).getLocations()[0], is("2-A.xml")); + assertThat(level3Config).hasSize(1); + assertThat(level3Config.get(0).getLocations()[0]).isEqualTo("2-A.xml"); // ... List level7Config = map.get(level7); - assertThat(level7Config.size(), is(1)); - assertThat(level7Config.get(0).getLocations()[0], is("3-C.xml")); + assertThat(level7Config).hasSize(1); + assertThat(level7Config.get(0).getLocations()[0]).isEqualTo("3-C.xml"); } @Test @@ -299,25 +294,24 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf String level2 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 2; String level3 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 3; - assertThat(map.size(), is(3)); - assertThat(map.keySet(), hasItems(level1, level2, level3)); + assertThat(map).hasSize(3).containsKeys(level1, level2, level3); Iterator levels = map.keySet().iterator(); - assertThat(levels.next(), is(level1)); - assertThat(levels.next(), is(level2)); - assertThat(levels.next(), is(level3)); + assertThat(levels.next()).isEqualTo(level1); + assertThat(levels.next()).isEqualTo(level2); + assertThat(levels.next()).isEqualTo(level3); List level1Config = map.get(level1); - assertThat(level1Config.size(), is(2)); - assertThat(level1Config.get(0).getLocations()[0], is("1-A.xml")); - assertThat(level1Config.get(1).getLocations()[0], is("2-A.xml")); + assertThat(level1Config).hasSize(2); + assertThat(level1Config.get(0).getLocations()[0]).isEqualTo("1-A.xml"); + assertThat(level1Config.get(1).getLocations()[0]).isEqualTo("2-A.xml"); List level2Config = map.get(level2); - assertThat(level2Config.size(), is(1)); - assertThat(level2Config.get(0).getLocations()[0], is("1-B.xml")); + assertThat(level2Config).hasSize(1); + assertThat(level2Config.get(0).getLocations()[0]).isEqualTo("1-B.xml"); List level3Config = map.get(level3); - assertThat(level3Config.size(), is(1)); - assertThat(level3Config.get(0).getLocations()[0], is("2-C.xml")); + assertThat(level3Config).hasSize(1); + assertThat(level3Config.get(0).getLocations()[0]).isEqualTo("2-C.xml"); } private void assertContextConfigEntriesAreNotUnique(Class testClass) { @@ -344,25 +338,24 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchiesAndOverriddenInitializers() { Map> map = buildContextHierarchyMap(TestClass2WithMultiLevelContextHierarchyWithOverriddenInitializers.class); - assertThat(map.size(), is(2)); - assertThat(map.keySet(), hasItems("alpha", "beta")); + assertThat(map).hasSize(2).containsKeys("alpha", "beta"); List alphaConfig = map.get("alpha"); - assertThat(alphaConfig.size(), is(2)); - assertThat(alphaConfig.get(0).getLocations().length, is(1)); - assertThat(alphaConfig.get(0).getLocations()[0], is("1-A.xml")); - assertThat(alphaConfig.get(0).getInitializers().length, is(0)); - assertThat(alphaConfig.get(1).getLocations().length, is(0)); - assertThat(alphaConfig.get(1).getInitializers().length, is(1)); + assertThat(alphaConfig).hasSize(2); + assertThat(alphaConfig.get(0).getLocations().length).isEqualTo(1); + assertThat(alphaConfig.get(0).getLocations()[0]).isEqualTo("1-A.xml"); + assertThat(alphaConfig.get(0).getInitializers().length).isEqualTo(0); + assertThat(alphaConfig.get(1).getLocations().length).isEqualTo(0); + assertThat(alphaConfig.get(1).getInitializers().length).isEqualTo(1); assertEquals(DummyApplicationContextInitializer.class, alphaConfig.get(1).getInitializers()[0]); List betaConfig = map.get("beta"); - assertThat(betaConfig.size(), is(2)); - assertThat(betaConfig.get(0).getLocations().length, is(1)); - assertThat(betaConfig.get(0).getLocations()[0], is("1-B.xml")); - assertThat(betaConfig.get(0).getInitializers().length, is(0)); - assertThat(betaConfig.get(1).getLocations().length, is(0)); - assertThat(betaConfig.get(1).getInitializers().length, is(1)); + assertThat(betaConfig).hasSize(2); + assertThat(betaConfig.get(0).getLocations().length).isEqualTo(1); + assertThat(betaConfig.get(0).getLocations()[0]).isEqualTo("1-B.xml"); + assertThat(betaConfig.get(0).getInitializers().length).isEqualTo(0); + assertThat(betaConfig.get(1).getLocations().length).isEqualTo(0); + assertThat(betaConfig.get(1).getInitializers().length).isEqualTo(1); assertEquals(DummyApplicationContextInitializer.class, betaConfig.get(1).getInitializers()[0]); } diff --git a/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java index c488ad543b..23c7201aae 100644 --- a/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java @@ -23,8 +23,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.jdbc.core.JdbcTemplate; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -45,21 +44,21 @@ public class JdbcTestUtilsTests { public void deleteWithoutWhereClause() throws Exception { given(jdbcTemplate.update("DELETE FROM person")).willReturn(10); int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", null); - assertThat(deleted, equalTo(10)); + assertThat(deleted).isEqualTo(10); } @Test public void deleteWithWhereClause() throws Exception { given(jdbcTemplate.update("DELETE FROM person WHERE name = 'Bob' and age > 25")).willReturn(10); int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", "name = 'Bob' and age > 25"); - assertThat(deleted, equalTo(10)); + assertThat(deleted).isEqualTo(10); } @Test public void deleteWithWhereClauseAndArguments() throws Exception { given(jdbcTemplate.update("DELETE FROM person WHERE name = ? and age > ?", "Bob", 25)).willReturn(10); int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", "name = ? and age > ?", "Bob", 25); - assertThat(deleted, equalTo(10)); + assertThat(deleted).isEqualTo(10); } } diff --git a/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java index a83b86d431..1b919e7d31 100644 --- a/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java @@ -21,9 +21,8 @@ import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -131,7 +130,7 @@ public class AopTestUtilsTests { pf.addInterface(Foo.class); Foo proxy = (Foo) pf.getProxy(); assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy)); - assertThat(proxy, instanceOf(Foo.class)); + assertThat(proxy).isInstanceOf(Foo.class); return proxy; } @@ -141,7 +140,7 @@ public class AopTestUtilsTests { pf.setProxyTargetClass(true); Foo proxy = (Foo) pf.getProxy(); assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy)); - assertThat(proxy, instanceOf(FooImpl.class)); + assertThat(proxy).isInstanceOf(FooImpl.class); return proxy; } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java index dd57c3d860..0adb1e4355 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java @@ -29,6 +29,7 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.hasXPath; + /** * Unit tests for {@link ContentRequestMatchers}. * diff --git a/spring-test/src/test/java/org/springframework/test/web/client/match/JsonPathRequestMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/client/match/JsonPathRequestMatchersTests.java index 67b9f53f98..ef0415c696 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/match/JsonPathRequestMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/match/JsonPathRequestMatchersTests.java @@ -23,7 +23,8 @@ import org.junit.Test; import org.springframework.mock.http.client.MockClientHttpRequest; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.equalTo; + /** * Unit tests for {@link JsonPathRequestMatchers}. diff --git a/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java index 7d3c2cd9b3..060f53c6e7 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.http.client.MockClientHttpRequest; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -83,7 +83,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.method(HttpMethod.GET).match(this.request)); - assertThat(error.getMessage(), containsString("expected: but was:")); + assertThat(error.getMessage()).contains("expected: but was:"); } @Test @@ -97,7 +97,7 @@ public class MockRestRequestMatchersTests { public void headerMissing() throws Exception { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.header("foo", "bar").match(this.request)); - assertThat(error.getMessage(), containsString("was null")); + assertThat(error.getMessage()).contains("was null"); } @Test @@ -106,7 +106,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.header("foo", "bad").match(this.request)); - assertThat(error.getMessage(), containsString("expected: but was:")); + assertThat(error.getMessage()).contains("expected: but was:"); } @Test @@ -120,7 +120,7 @@ public class MockRestRequestMatchersTests { public void headerContainsWithMissingHeader() throws Exception { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.header("foo", containsString("baz")).match(this.request)); - assertThat(error.getMessage(), containsString("but was null")); + assertThat(error.getMessage()).contains("but was null"); } @Test @@ -129,7 +129,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.header("foo", containsString("bx")).match(this.request)); - assertThat(error.getMessage(), containsString("was \"bar\"")); + assertThat(error.getMessage()).contains("was \"bar\""); } @Test @@ -143,7 +143,7 @@ public class MockRestRequestMatchersTests { public void headersWithMissingHeader() throws Exception { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.header("foo", "bar").match(this.request)); - assertThat(error.getMessage(), containsString("but was null")); + assertThat(error.getMessage()).contains("but was null"); } @Test @@ -152,7 +152,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request)); - assertThat(error.getMessage(), containsString("to have at least <2> values")); + assertThat(error.getMessage()).contains("to have at least <2> values"); } @Test @@ -168,7 +168,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.queryParam("foo", "bar").match(this.request)); - assertThat(error.getMessage(), containsString("but was null")); + assertThat(error.getMessage()).contains("but was null"); } @Test @@ -177,7 +177,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.queryParam("foo", "bad").match(this.request)); - assertThat(error.getMessage(), containsString("expected: but was:")); + assertThat(error.getMessage()).contains("expected: but was:"); } @Test @@ -193,7 +193,7 @@ public class MockRestRequestMatchersTests { AssertionError error = assertThrows(AssertionError.class, () -> MockRestRequestMatchers.queryParam("foo", containsString("bx")).match(this.request)); - assertThat(error.getMessage(), containsString("was \"bar\"")); + assertThat(error.getMessage()).contains("was \"bar\""); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/HeaderAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/HeaderAssertionTests.java index e9a35b4697..e5a15ad43b 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/HeaderAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/HeaderAssertionTests.java @@ -35,7 +35,7 @@ import org.springframework.mock.http.client.reactive.MockClientHttpResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; /** diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerSpecTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerSpecTests.java index 942c1a0f23..4917372079 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerSpecTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerSpecTests.java @@ -27,8 +27,7 @@ import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringContains.containsString; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AbstractMockServerSpec}. @@ -56,7 +55,7 @@ public class MockServerSpecTests { .exchange() .expectBody(String.class) .consumeWith(result -> assertThat( - result.getResponseBody(), containsString("test-attribute=:A:B"))); + result.getResponseBody()).contains("test-attribute=:A:B")); } @Test @@ -80,7 +79,7 @@ public class MockServerSpecTests { .exchange() .expectBody(String.class) .consumeWith(result -> assertThat( - result.getResponseBody(), containsString("test-attribute=:Fwk-A:Fwk-B:App-A:App-B"))); + result.getResponseBody()).contains("test-attribute=:Fwk-A:Fwk-B:App-A:App-B")); } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java index 1a087a5248..0d0f9c7a65 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java @@ -33,6 +33,8 @@ import org.springframework.web.bind.annotation.RestController; import static org.hamcrest.Matchers.containsString; + + /** * Samples of tests using {@link WebTestClient} with serialized JSON content. * diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java index e774942993..7f616e9f3b 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java @@ -22,7 +22,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.hamcrest.MatcherAssert; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; @@ -40,10 +39,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static java.time.Duration.ofMillis; -import static org.hamcrest.CoreMatchers.endsWith; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.springframework.http.MediaType.TEXT_EVENT_STREAM; @@ -110,7 +107,7 @@ public class ResponseEntityTests { .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBodyList(Person.class).value(people -> - MatcherAssert.assertThat(people, hasItem(new Person("Jason"))) + assertThat(people).contains(new Person("Jason")) ); } @@ -141,7 +138,7 @@ public class ResponseEntityTests { StepVerifier.create(result.getResponseBody()) .expectNext(new Person("N0"), new Person("N1"), new Person("N2")) .expectNextCount(4) - .consumeNextWith(person -> assertThat(person.getName(), endsWith("7"))) + .consumeNextWith(person -> assertThat(person.getName()).endsWith("7")) .thenCancel() .verify(); } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java index cd50a87430..faf18f6c6a 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java @@ -40,6 +40,8 @@ import org.springframework.web.bind.annotation.RestController; import static org.hamcrest.Matchers.startsWith; + + /** * Samples of tests using {@link WebTestClient} with XML content. * diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/MockMvcReuseTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/MockMvcReuseTests.java index f13ad7665d..c5744f23e0 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/MockMvcReuseTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/MockMvcReuseTests.java @@ -31,7 +31,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.nullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java index de0d563861..d3e9c56c26 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java @@ -39,11 +39,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.core.IsNot.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -95,7 +91,7 @@ public class DelegatingWebConnectionTests { given(defaultConnection.getResponse(request)).willReturn(expectedResponse); WebResponse response = webConnection.getResponse(request); - assertThat(response, sameInstance(expectedResponse)); + assertThat(response).isSameAs(expectedResponse); verify(matcher1).matches(request); verify(matcher2).matches(request); verifyNoMoreInteractions(connection1, connection2); @@ -108,7 +104,7 @@ public class DelegatingWebConnectionTests { given(connection1.getResponse(request)).willReturn(expectedResponse); WebResponse response = webConnection.getResponse(request); - assertThat(response, sameInstance(expectedResponse)); + assertThat(response).isSameAs(expectedResponse); verify(matcher1).matches(request); verifyNoMoreInteractions(matcher2, connection2, defaultConnection); verify(connection1).getResponse(request); @@ -120,7 +116,7 @@ public class DelegatingWebConnectionTests { given(connection2.getResponse(request)).willReturn(expectedResponse); WebResponse response = webConnection.getResponse(request); - assertThat(response, sameInstance(expectedResponse)); + assertThat(response).isSameAs(expectedResponse); verify(matcher1).matches(request); verify(matcher2).matches(request); verifyNoMoreInteractions(connection1, defaultConnection); @@ -142,8 +138,8 @@ public class DelegatingWebConnectionTests { new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection))); Page page = webClient.getPage("https://code.jquery.com/jquery-1.11.0.min.js"); - assertThat(page.getWebResponse().getStatusCode(), equalTo(200)); - assertThat(page.getWebResponse().getContentAsString(), not(isEmptyString())); + assertThat(page.getWebResponse().getStatusCode()).isEqualTo(200); + assertThat(page.getWebResponse().getContentAsString()).isNotEmpty(); } 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 4d00dc2451..f61603f737 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 @@ -19,9 +19,9 @@ package org.springframework.test.web.servlet.htmlunit; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.ServletContext; @@ -45,16 +45,8 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; /** @@ -119,8 +111,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getAuthType(), equalTo("Basic")); - assertThat(actualRequest.getHeader("Authorization"), equalTo(authzHeaderValue)); + assertThat(actualRequest.getAuthType()).isEqualTo("Basic"); + assertThat(actualRequest.getHeader("Authorization")).isEqualTo(authzHeaderValue); } @Test @@ -129,14 +121,14 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getCharacterEncoding(), equalTo("UTF-8")); + assertThat(actualRequest.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void buildRequestDefaultCharacterEncoding() { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getCharacterEncoding(), equalTo("ISO-8859-1")); + assertThat(actualRequest.getCharacterEncoding()).isEqualTo("ISO-8859-1"); } @Test @@ -147,7 +139,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getContentLength(), equalTo(content.length())); + assertThat(actualRequest.getContentLength()).isEqualTo(content.length()); } @Test @@ -157,8 +149,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getContentType(), equalTo(contentType)); - assertThat(actualRequest.getHeader("Content-Type"), equalTo(contentType)); + assertThat(actualRequest.getContentType()).isEqualTo(contentType); + assertThat(actualRequest.getHeader("Content-Type")).isEqualTo(contentType); } @Test // SPR-14916 @@ -167,9 +159,9 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getContentType(), equalTo("application/x-www-form-urlencoded")); - assertThat(actualRequest.getHeader("Content-Type"), - equalTo("application/x-www-form-urlencoded;charset=ISO-8859-1")); + assertThat(actualRequest.getContentType()).isEqualTo("application/x-www-form-urlencoded"); + assertThat(actualRequest.getHeader("Content-Type")) + .isEqualTo("application/x-www-form-urlencoded;charset=ISO-8859-1"); } @@ -177,7 +169,7 @@ public class HtmlUnitRequestBuilderTests { public void buildRequestContextPathUsesFirstSegmentByDefault() { String contextPath = requestBuilder.buildRequest(servletContext).getContextPath(); - assertThat(contextPath, equalTo("/test")); + assertThat(contextPath).isEqualTo("/test"); } @Test @@ -185,7 +177,7 @@ public class HtmlUnitRequestBuilderTests { webRequest.setUrl(new URL("http://example.com/")); String contextPath = requestBuilder.buildRequest(servletContext).getContextPath(); - assertThat(contextPath, equalTo("")); + assertThat(contextPath).isEqualTo(""); } @Test @@ -203,7 +195,7 @@ public class HtmlUnitRequestBuilderTests { String contextPath = requestBuilder.buildRequest(servletContext).getContextPath(); - assertThat(contextPath, equalTo(expected)); + assertThat(contextPath).isEqualTo(expected); } @Test @@ -213,7 +205,7 @@ public class HtmlUnitRequestBuilderTests { String contextPath = requestBuilder.buildRequest(servletContext).getContextPath(); - assertThat(contextPath, equalTo(expected)); + assertThat(contextPath).isEqualTo(expected); } @Test @@ -223,14 +215,14 @@ public class HtmlUnitRequestBuilderTests { String contextPath = requestBuilder.buildRequest(servletContext).getContextPath(); - assertThat(contextPath, equalTo(expected)); + assertThat(contextPath).isEqualTo(expected); } @Test public void buildRequestCookiesNull() { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getCookies(), nullValue()); + assertThat(actualRequest.getCookies()).isNull(); } @Test @@ -240,9 +232,9 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); Cookie[] cookies = actualRequest.getCookies(); - assertThat(cookies.length, equalTo(1)); - assertThat(cookies[0].getName(), equalTo("name")); - assertThat(cookies[0].getValue(), equalTo("value")); + assertThat(cookies.length).isEqualTo(1); + assertThat(cookies[0].getName()).isEqualTo("name"); + assertThat(cookies[0].getValue()).isEqualTo("value"); } @Test @@ -252,13 +244,13 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); Cookie[] cookies = actualRequest.getCookies(); - assertThat(cookies.length, equalTo(2)); + assertThat(cookies.length).isEqualTo(2); Cookie cookie = cookies[0]; - assertThat(cookie.getName(), equalTo("name")); - assertThat(cookie.getValue(), equalTo("value")); + assertThat(cookie.getName()).isEqualTo("name"); + assertThat(cookie.getValue()).isEqualTo("value"); cookie = cookies[1]; - assertThat(cookie.getName(), equalTo("name2")); - assertThat(cookie.getValue(), equalTo("value2")); + assertThat(cookie.getName()).isEqualTo("name2"); + assertThat(cookie.getValue()).isEqualTo("value2"); } @Test @@ -270,21 +262,21 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(IOUtils.toString(actualRequest.getInputStream()), equalTo(content)); + assertThat(IOUtils.toString(actualRequest.getInputStream())).isEqualTo(content); } @Test public void buildRequestLocalAddr() { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocalAddr(), equalTo("127.0.0.1")); + assertThat(actualRequest.getLocalAddr()).isEqualTo("127.0.0.1"); } @Test public void buildRequestLocaleDefault() { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocale(), equalTo(Locale.getDefault())); + assertThat(actualRequest.getLocale()).isEqualTo(Locale.getDefault()); } @Test @@ -293,7 +285,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocale(), equalTo(new Locale("da"))); + assertThat(actualRequest.getLocale()).isEqualTo(new Locale("da")); } @Test @@ -302,7 +294,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocale(), equalTo(new Locale("en", "gb"))); + assertThat(actualRequest.getLocale()).isEqualTo(new Locale("en", "gb")); } @Test @@ -311,7 +303,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocale(), equalTo(new Locale("en", ""))); + assertThat(actualRequest.getLocale()).isEqualTo(new Locale("en", "")); } @Test @@ -320,7 +312,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocale(), equalTo(Locale.US)); + assertThat(actualRequest.getLocale()).isEqualTo(Locale.US); } @Test @@ -329,7 +321,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocale(), equalTo(Locale.FRENCH)); + assertThat(actualRequest.getLocale()).isEqualTo(Locale.FRENCH); } @Test @@ -338,22 +330,22 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - List expected = asList(new Locale("da"), new Locale("en", "gb"), new Locale("en", "")); - assertThat(Collections.list(actualRequest.getLocales()), equalTo(expected)); + assertThat(Collections.list(actualRequest.getLocales())) + .containsExactly(new Locale("da"), new Locale("en", "gb"), new Locale("en", "")); } @Test public void buildRequestLocalName() { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocalName(), equalTo("localhost")); + assertThat(actualRequest.getLocalName()).isEqualTo("localhost"); } @Test public void buildRequestLocalPort() { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocalPort(), equalTo(80)); + assertThat(actualRequest.getLocalPort()).isEqualTo(80); } @Test @@ -361,7 +353,7 @@ public class HtmlUnitRequestBuilderTests { webRequest.setUrl(new URL("http://localhost/test/this")); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getLocalPort(), equalTo(-1)); + assertThat(actualRequest.getLocalPort()).isEqualTo(-1); } @Test @@ -369,59 +361,59 @@ public class HtmlUnitRequestBuilderTests { for (HttpMethod expectedMethod : HttpMethod.values()) { webRequest.setHttpMethod(expectedMethod); String actualMethod = requestBuilder.buildRequest(servletContext).getMethod(); - assertThat(actualMethod, equalTo(expectedMethod.name())); + assertThat(actualMethod).isEqualTo(expectedMethod.name()); } } @Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParam() { - webRequest.setRequestParameters(asList(new NameValuePair("name", "value"))); + webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", "value"))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo("value")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo("value"); } @Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithNullValue() { - webRequest.setRequestParameters(asList(new NameValuePair("name", null))); + webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", null))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), nullValue()); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isNull(); } @Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithEmptyValue() { - webRequest.setRequestParameters(asList(new NameValuePair("name", ""))); + webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", ""))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo("")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo(""); } @Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithValueSetToSpace() { - webRequest.setRequestParameters(asList(new NameValuePair("name", " "))); + webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", " "))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo(" ")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo(" "); } @Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithMultipleRequestParams() { - webRequest.setRequestParameters(asList(new NameValuePair("name1", "value1"), new NameValuePair("name2", "value2"))); + webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name1", "value1"), new NameValuePair("name2", "value2"))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(2)); - assertThat(actualRequest.getParameter("name1"), equalTo("value1")); - assertThat(actualRequest.getParameter("name2"), equalTo("value2")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(2); + assertThat(actualRequest.getParameter("name1")).isEqualTo("value1"); + assertThat(actualRequest.getParameter("name2")).isEqualTo("value2"); } @Test @@ -430,8 +422,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo("value")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo("value"); } // SPR-14177 @@ -441,8 +433,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("row[0]"), equalTo("value")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("row[0]")).isEqualTo("value"); } @Test @@ -451,8 +443,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo("row[0]")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo("row[0]"); } @Test @@ -461,8 +453,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo("")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo(""); } @Test @@ -471,8 +463,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo("")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo(""); } @Test @@ -481,8 +473,8 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(1)); - assertThat(actualRequest.getParameter("name"), equalTo(" ")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(1); + assertThat(actualRequest.getParameter("name")).isEqualTo(" "); } @Test @@ -491,16 +483,16 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getParameterMap().size(), equalTo(2)); - assertThat(actualRequest.getParameter("name"), equalTo("value")); - assertThat(actualRequest.getParameter("param2"), equalTo("value 2")); + assertThat(actualRequest.getParameterMap().size()).isEqualTo(2); + assertThat(actualRequest.getParameter("name")).isEqualTo("value"); + assertThat(actualRequest.getParameter("param2")).isEqualTo("value 2"); } @Test public void buildRequestPathInfo() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getPathInfo(), nullValue()); + assertThat(actualRequest.getPathInfo()).isNull(); } @Test @@ -509,7 +501,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getPathInfo(), nullValue()); + assertThat(actualRequest.getPathInfo()).isNull(); } @Test @@ -519,15 +511,15 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); // verify it is going to work with Spring Security's AntPathRequestMatcher - assertThat(actualRequest.getPathInfo(), nullValue()); - assertThat(actualRequest.getServletPath(), equalTo("/login/authenticate")); + assertThat(actualRequest.getPathInfo()).isNull(); + assertThat(actualRequest.getServletPath()).isEqualTo("/login/authenticate"); } @Test public void buildRequestProtocol() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getProtocol(), equalTo("HTTP/1.1")); + assertThat(actualRequest.getProtocol()).isEqualTo("HTTP/1.1"); } @Test @@ -537,7 +529,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getQueryString(), equalTo(expectedQuery)); + assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery); } @Test @@ -547,7 +539,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getQueryString(), equalTo(expectedQuery)); + assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery); } @Test @@ -557,7 +549,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getQueryString(), equalTo(expectedQuery)); + assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery); } @Test @@ -567,7 +559,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getQueryString(), equalTo(expectedQuery)); + assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery); } @Test @@ -577,7 +569,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getQueryString(), equalTo(expectedQuery)); + assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery); } @Test @@ -588,28 +580,28 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(IOUtils.toString(actualRequest.getReader()), equalTo(expectedBody)); + assertThat(IOUtils.toString(actualRequest.getReader())).isEqualTo(expectedBody); } @Test public void buildRequestRemoteAddr() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRemoteAddr(), equalTo("127.0.0.1")); + assertThat(actualRequest.getRemoteAddr()).isEqualTo("127.0.0.1"); } @Test public void buildRequestRemoteHost() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRemoteAddr(), equalTo("127.0.0.1")); + assertThat(actualRequest.getRemoteAddr()).isEqualTo("127.0.0.1"); } @Test public void buildRequestRemotePort() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRemotePort(), equalTo(80)); + assertThat(actualRequest.getRemotePort()).isEqualTo(80); } @Test @@ -618,7 +610,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRemotePort(), equalTo(8080)); + assertThat(actualRequest.getRemotePort()).isEqualTo(8080); } @Test @@ -627,7 +619,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRemotePort(), equalTo(80)); + assertThat(actualRequest.getRemotePort()).isEqualTo(80); } @Test @@ -636,33 +628,33 @@ public class HtmlUnitRequestBuilderTests { webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRequestedSessionId(), equalTo(sessionId)); + assertThat(actualRequest.getRequestedSessionId()).isEqualTo(sessionId); } @Test public void buildRequestRequestedSessionIdNull() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getRequestedSessionId(), nullValue()); + assertThat(actualRequest.getRequestedSessionId()).isNull(); } @Test public void buildRequestUri() { String uri = requestBuilder.buildRequest(servletContext).getRequestURI(); - assertThat(uri, equalTo("/test/this/here")); + assertThat(uri).isEqualTo("/test/this/here"); } @Test public void buildRequestUrl() { String uri = requestBuilder.buildRequest(servletContext).getRequestURL().toString(); - assertThat(uri, equalTo("http://example.com/test/this/here")); + assertThat(uri).isEqualTo("http://example.com/test/this/here"); } @Test public void buildRequestSchemeHttp() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getScheme(), equalTo("http")); + assertThat(actualRequest.getScheme()).isEqualTo("http"); } @Test @@ -670,21 +662,21 @@ public class HtmlUnitRequestBuilderTests { webRequest.setUrl(new URL("https://example.com/")); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getScheme(), equalTo("https")); + assertThat(actualRequest.getScheme()).isEqualTo("https"); } @Test public void buildRequestServerName() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getServerName(), equalTo("example.com")); + assertThat(actualRequest.getServerName()).isEqualTo("example.com"); } @Test public void buildRequestServerPort() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getServerPort(), equalTo(80)); + assertThat(actualRequest.getServerPort()).isEqualTo(80); } @Test @@ -692,21 +684,21 @@ public class HtmlUnitRequestBuilderTests { webRequest.setUrl(new URL("https://example.com/")); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getServerPort(), equalTo(-1)); + assertThat(actualRequest.getServerPort()).isEqualTo(-1); } @Test public void buildRequestServletContext() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getServletContext(), equalTo(servletContext)); + assertThat(actualRequest.getServletContext()).isEqualTo(servletContext); } @Test public void buildRequestServletPath() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getServletPath(), equalTo("/this/here")); + assertThat(actualRequest.getServletPath()).isEqualTo("/this/here"); } @Test @@ -714,7 +706,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); HttpSession newSession = actualRequest.getSession(); - assertThat(newSession, notNullValue()); + assertThat(newSession).isNotNull(); assertSingleSessionCookie( "JSESSIONID=" + newSession.getId() + "; Path=/test; Domain=example.com"); @@ -723,7 +715,7 @@ public class HtmlUnitRequestBuilderTests { requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest); actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getSession(), sameInstance(newSession)); + assertThat(actualRequest.getSession()).isSameAs(newSession); } @Test @@ -733,16 +725,16 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); HttpSession session = actualRequest.getSession(); - assertThat(session.getId(), equalTo(sessionId)); + assertThat(session.getId()).isEqualTo(sessionId); assertSingleSessionCookie("JSESSIONID=" + session.getId() + "; Path=/test; Domain=example.com"); requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest); actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getSession(), equalTo(session)); + assertThat(actualRequest.getSession()).isEqualTo(session); webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId + "NEW"); actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getSession(), not(equalTo(session))); + assertThat(actualRequest.getSession()).isNotEqualTo(session); assertSingleSessionCookie("JSESSIONID=" + actualRequest.getSession().getId() + "; Path=/test; Domain=example.com"); } @@ -752,7 +744,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); HttpSession session = actualRequest.getSession(true); - assertThat(session, notNullValue()); + assertThat(session).isNotNull(); } @Test @@ -760,7 +752,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); HttpSession session = actualRequest.getSession(false); - assertThat(session, nullValue()); + assertThat(session).isNull(); } @Test @@ -770,14 +762,14 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); HttpSession session = actualRequest.getSession(false); - assertThat(session, notNullValue()); + assertThat(session).isNotNull(); } @Test public void buildRequestSessionIsNew() throws Exception { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getSession().isNew(), equalTo(true)); + assertThat(actualRequest.getSession().isNew()).isEqualTo(true); } @Test @@ -787,7 +779,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getSession().isNew(), equalTo(false)); + assertThat(actualRequest.getSession().isNew()).isEqualTo(false); } @Test @@ -799,7 +791,7 @@ public class HtmlUnitRequestBuilderTests { HttpSession sessionToRemove = actualRequest.getSession(); sessionToRemove.invalidate(); - assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false)); + assertThat(sessions.containsKey(sessionToRemove.getId())).isEqualTo(false); assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId() + "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com"); @@ -808,8 +800,8 @@ public class HtmlUnitRequestBuilderTests { actualRequest = requestBuilder.buildRequest(servletContext); - assertThat(actualRequest.getSession().isNew(), equalTo(true)); - assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false)); + assertThat(actualRequest.getSession().isNew()).isEqualTo(true); + assertThat(sessions.containsKey(sessionToRemove.getId())).isEqualTo(false); } // --- setContextPath @@ -818,14 +810,14 @@ public class HtmlUnitRequestBuilderTests { public void setContextPathNull() { requestBuilder.setContextPath(null); - assertThat(getContextPath(), nullValue()); + assertThat(getContextPath()).isNull(); } @Test public void setContextPathEmptyString() { requestBuilder.setContextPath(""); - assertThat(getContextPath(), isEmptyString()); + assertThat(getContextPath()).isEmpty(); } @Test @@ -845,7 +837,7 @@ public class HtmlUnitRequestBuilderTests { String expectedContextPath = "/abc/def"; requestBuilder.setContextPath(expectedContextPath); - assertThat(getContextPath(), equalTo(expectedContextPath)); + assertThat(getContextPath()).isEqualTo(expectedContextPath); } @Test @@ -856,7 +848,7 @@ public class HtmlUnitRequestBuilderTests { .defaultRequest(get("/").header(headerName, headerValue)) .build(); - assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getHeader(headerName), equalTo(headerValue)); + assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getHeader(headerName)).isEqualTo(headerValue); } @Test @@ -867,7 +859,7 @@ public class HtmlUnitRequestBuilderTests { .defaultRequest(get("/").sessionAttr(attrName, attrValue)) .build(); - assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName), equalTo(attrValue)); + assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName)).isEqualTo(attrValue); } @Test @@ -876,7 +868,7 @@ public class HtmlUnitRequestBuilderTests { .defaultRequest(get("/")) .build(); - assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession(false), nullValue()); + assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession(false)).isNull(); } @Test @@ -889,7 +881,7 @@ public class HtmlUnitRequestBuilderTests { .build(); MockHttpServletRequest performedRequest = mockMvc.perform(requestBuilder).andReturn().getRequest(); - assertThat(asList(performedRequest.getParameterValues(paramName)), contains(paramValue, paramValue2)); + assertThat(performedRequest.getParameterValues(paramName)).containsExactly(paramValue, paramValue2); } @Test @@ -901,11 +893,11 @@ public class HtmlUnitRequestBuilderTests { .build(); Cookie[] cookies = mockMvc.perform(requestBuilder).andReturn().getRequest().getCookies(); - assertThat(cookies, notNullValue()); - assertThat(cookies.length, equalTo(1)); + assertThat(cookies).isNotNull(); + assertThat(cookies.length).isEqualTo(1); Cookie cookie = cookies[0]; - assertThat(cookie.getName(), equalTo(cookieName)); - assertThat(cookie.getValue(), equalTo(cookieValue)); + assertThat(cookie.getName()).isEqualTo(cookieName); + assertThat(cookie.getValue()).isEqualTo(cookieValue); } @Test @@ -916,7 +908,7 @@ public class HtmlUnitRequestBuilderTests { .defaultRequest(get("/").requestAttr(attrName, attrValue)) .build(); - assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getAttribute(attrName), equalTo(attrValue)); + assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getAttribute(attrName)).isEqualTo(attrValue); } @Test // SPR-14584 @@ -926,22 +918,22 @@ public class HtmlUnitRequestBuilderTests { .defaultRequest(get("/")) .build(); - assertThat(mockMvc.perform(get(pathInfo)).andReturn().getRequest().getPathInfo(), equalTo(pathInfo)); + assertThat(mockMvc.perform(get(pathInfo)).andReturn().getRequest().getPathInfo()).isEqualTo(pathInfo); mockMvc.perform(requestBuilder); - assertThat(mockMvc.perform(get(pathInfo)).andReturn().getRequest().getPathInfo(), equalTo(pathInfo)); + assertThat(mockMvc.perform(get(pathInfo)).andReturn().getRequest().getPathInfo()).isEqualTo(pathInfo); } private void assertSingleSessionCookie(String expected) { com.gargoylesoftware.htmlunit.util.Cookie jsessionidCookie = webClient.getCookieManager().getCookie("JSESSIONID"); if (expected == null || expected.contains("Expires=Thu, 01-Jan-1970 00:00:01 GMT")) { - assertThat(jsessionidCookie, nullValue()); + assertThat(jsessionidCookie).isNull(); return; } String actual = jsessionidCookie.getValue(); - assertThat("JSESSIONID=" + actual + "; Path=/test; Domain=example.com", equalTo(expected)); + assertThat("JSESSIONID=" + actual + "; Path=/test; Domain=example.com").isEqualTo(expected); } private String getContextPath() { 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 bdc605e697..4a93942a28 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 @@ -40,11 +40,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.notNullValue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -123,22 +120,22 @@ public class MockMvcConnectionBuilderSupportTests { @Test public void defaultContextPathEmpty() throws Exception { WebConnection conn = this.builder.createConnection(this.client); - assertThat(getResponse(conn, "http://localhost/abc").getContentAsString(), equalTo("")); + assertThat(getResponse(conn, "http://localhost/abc").getContentAsString()).isEqualTo(""); } @Test public void defaultContextPathCustom() throws Exception { WebConnection conn = this.builder.contextPath("/abc").createConnection(this.client); - assertThat(getResponse(conn, "http://localhost/abc/def").getContentAsString(), equalTo("/abc")); + assertThat(getResponse(conn, "http://localhost/abc/def").getContentAsString()).isEqualTo("/abc"); } private void assertMockMvcUsed(WebConnection connection, String url) throws Exception { - assertThat(getResponse(connection, url), notNullValue()); + assertThat(getResponse(connection, url)).isNotNull(); } private void assertMockMvcNotUsed(WebConnection connection, String url) throws Exception { - assertThat(getResponse(connection, url), nullValue()); + assertThat(getResponse(connection, url)).isNull(); } private WebResponse getResponse(WebConnection connection, String url) throws IOException { diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java index 69fed6a802..2b63efbf6a 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java @@ -48,10 +48,9 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; + /** * Integration tests for {@link MockMvcWebClientBuilder}. @@ -112,9 +111,9 @@ public class MockMvcWebClientBuilderTests { this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build(); WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build(); - assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("NA")); + assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("NA"); client.getCookieManager().addCookie(new Cookie("localhost", "cookie", "cookieManagerShared")); - assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("cookieManagerShared")); + assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("cookieManagerShared"); } @Test // SPR-14265 @@ -122,19 +121,19 @@ public class MockMvcWebClientBuilderTests { this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build(); WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build(); - assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("NA")); - assertThat(postResponse(client, "http://localhost/?cookie=foo").getContentAsString(), equalTo("Set")); - assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("foo")); - assertThat(deleteResponse(client, "http://localhost/").getContentAsString(), equalTo("Delete")); - assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("NA")); + assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("NA"); + assertThat(postResponse(client, "http://localhost/?cookie=foo").getContentAsString()).isEqualTo("Set"); + assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("foo"); + assertThat(deleteResponse(client, "http://localhost/").getContentAsString()).isEqualTo("Delete"); + assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("NA"); } private void assertMockMvcUsed(WebClient client, String url) throws Exception { - assertThat(getResponse(client, url).getContentAsString(), equalTo("mvc")); + assertThat(getResponse(client, url).getContentAsString()).isEqualTo("mvc"); } private void assertMockMvcNotUsed(WebClient client, String url) throws Exception { - assertThat(getResponse(client, url).getContentAsString(), not(equalTo("mvc"))); + assertThat(getResponse(client, url).getContentAsString()).isNotEqualTo("mvc"); } private WebResponse getResponse(WebClient client, String url) throws IOException { diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java index e4bb818e4a..aff8add4c1 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java @@ -29,8 +29,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; + /** * Integration tests for {@link MockMvcWebConnection}. @@ -50,14 +49,14 @@ public class MockMvcWebConnectionTests { public void contextPathNull() throws IOException { this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, null)); Page page = this.webClient.getPage("http://localhost/context/a"); - assertThat(page.getWebResponse().getStatusCode(), equalTo(200)); + assertThat(page.getWebResponse().getStatusCode()).isEqualTo(200); } @Test public void contextPathExplicit() throws IOException { this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, "/context")); Page page = this.webClient.getPage("http://localhost/context/a"); - assertThat(page.getWebResponse().getStatusCode(), equalTo(200)); + assertThat(page.getWebResponse().getStatusCode()).isEqualTo(200); } @Test @@ -78,7 +77,7 @@ public class MockMvcWebConnectionTests { public void forward() throws IOException { this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, "")); Page page = this.webClient.getPage("http://localhost/forward"); - assertThat(page.getWebResponse().getContentAsString(), equalTo("hello")); + assertThat(page.getWebResponse().getContentAsString()).isEqualTo("hello"); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockWebResponseBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockWebResponseBuilderTests.java index 697213f622..665e4fb9f3 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockWebResponseBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockWebResponseBuilderTests.java @@ -29,11 +29,9 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.endsWith; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; + /** * Tests for {@link MockWebResponseBuilder}. @@ -79,7 +77,7 @@ public class MockWebResponseBuilderTests { this.response.getWriter().write("expected content"); WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getContentAsString(), equalTo("expected content")); + assertThat(webResponse.getContentAsString()).isEqualTo("expected content"); } @Test @@ -87,7 +85,7 @@ public class MockWebResponseBuilderTests { this.response.addHeader("Content-Type", "text/html; charset=UTF-8"); WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getContentCharset(), equalTo(StandardCharsets.UTF_8)); + assertThat(webResponse.getContentCharset()).isEqualTo(StandardCharsets.UTF_8); } @Test @@ -95,7 +93,7 @@ public class MockWebResponseBuilderTests { this.response.addHeader("Content-Type", "text/html; charset-UTF-8"); WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getContentType(), equalTo("text/html")); + assertThat(webResponse.getContentType()).isEqualTo("text/html"); } @Test @@ -112,17 +110,18 @@ public class MockWebResponseBuilderTests { WebResponse webResponse = this.responseBuilder.build(); List responseHeaders = webResponse.getResponseHeaders(); - assertThat(responseHeaders.size(), equalTo(3)); + assertThat(responseHeaders.size()).isEqualTo(3); NameValuePair header = responseHeaders.get(0); - assertThat(header.getName(), equalTo("Content-Type")); - assertThat(header.getValue(), equalTo("text/html")); + assertThat(header.getName()).isEqualTo("Content-Type"); + assertThat(header.getValue()).isEqualTo("text/html"); header = responseHeaders.get(1); - assertThat(header.getName(), equalTo("X-Test")); - assertThat(header.getValue(), equalTo("value")); + assertThat(header.getName()).isEqualTo("X-Test"); + assertThat(header.getValue()).isEqualTo("value"); header = responseHeaders.get(2); - assertThat(header.getName(), equalTo("Set-Cookie")); - assertThat(header.getValue(), startsWith("cookieA=valueA; Path=/path; Domain=domain; Max-Age=1800; Expires=")); - assertThat(header.getValue(), endsWith("; Secure; HttpOnly")); + assertThat(header.getName()).isEqualTo("Set-Cookie"); + assertThat(header.getValue()) + .startsWith("cookieA=valueA; Path=/path; Domain=domain; Max-Age=1800; Expires=") + .endsWith("; Secure; HttpOnly"); } // SPR-14169 @@ -133,18 +132,18 @@ public class MockWebResponseBuilderTests { WebResponse webResponse = this.responseBuilder.build(); List responseHeaders = webResponse.getResponseHeaders(); - assertThat(responseHeaders.size(), equalTo(1)); + assertThat(responseHeaders.size()).isEqualTo(1); NameValuePair header = responseHeaders.get(0); - assertThat(header.getName(), equalTo("Set-Cookie")); - assertThat(header.getValue(), equalTo("cookieA=valueA")); + assertThat(header.getName()).isEqualTo("Set-Cookie"); + assertThat(header.getValue()).isEqualTo("cookieA=valueA"); } @Test public void buildStatus() throws Exception { WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getStatusCode(), equalTo(200)); - assertThat(webResponse.getStatusMessage(), equalTo("OK")); + assertThat(webResponse.getStatusCode()).isEqualTo(200); + assertThat(webResponse.getStatusMessage()).isEqualTo("OK"); } @Test @@ -152,8 +151,8 @@ public class MockWebResponseBuilderTests { this.response.setStatus(401); WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getStatusCode(), equalTo(401)); - assertThat(webResponse.getStatusMessage(), equalTo("Unauthorized")); + assertThat(webResponse.getStatusCode()).isEqualTo(401); + assertThat(webResponse.getStatusMessage()).isEqualTo("Unauthorized"); } @Test @@ -161,15 +160,15 @@ public class MockWebResponseBuilderTests { this.response.sendError(401, "Custom"); WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getStatusCode(), equalTo(401)); - assertThat(webResponse.getStatusMessage(), equalTo("Custom")); + assertThat(webResponse.getStatusCode()).isEqualTo(401); + assertThat(webResponse.getStatusMessage()).isEqualTo("Custom"); } @Test public void buildWebRequest() throws Exception { WebResponse webResponse = this.responseBuilder.build(); - assertThat(webResponse.getWebRequest(), equalTo(this.webRequest)); + assertThat(webResponse.getWebRequest()).isEqualTo(this.webRequest); } } 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 afc80171d1..c978f21f33 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 @@ -40,11 +40,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -124,19 +121,19 @@ public class MockMvcHtmlUnitDriverBuilderTests { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc) .withDelegate(otherDriver).build(); - assertThat(get("http://localhost/"), equalTo("")); + assertThat(get("http://localhost/")).isEqualTo(""); Cookie cookie = new Cookie("localhost", "cookie", "cookieManagerShared"); otherDriver.getWebClient().getCookieManager().addCookie(cookie); - assertThat(get("http://localhost/"), equalTo("cookieManagerShared")); + assertThat(get("http://localhost/")).isEqualTo("cookieManagerShared"); } private void assertMockMvcUsed(String url) throws Exception { - assertThat(get(url), containsString(EXPECTED_BODY)); + assertThat(get(url)).contains(EXPECTED_BODY); } private void assertMockMvcNotUsed(String url) throws Exception { - assertThat(get(url), not(containsString(EXPECTED_BODY))); + assertThat(get(url)).doesNotContain(EXPECTED_BODY); } private String get(String url) throws IOException { diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriverTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriverTests.java index 1f84ded56b..2871991374 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriverTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriverTests.java @@ -27,11 +27,9 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openqa.selenium.WebDriverException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.notNullValue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -58,7 +56,7 @@ public class WebConnectionHtmlUnitDriverTests { @Test public void getWebConnectionDefaultNotNull() { - assertThat(this.driver.getWebConnection(), notNullValue()); + assertThat(this.driver.getWebConnection()).isNotNull(); } @Test @@ -70,7 +68,7 @@ public class WebConnectionHtmlUnitDriverTests { @Test public void setWebConnection() { this.driver.setWebConnection(this.connection); - assertThat(this.driver.getWebConnection(), equalTo(this.connection)); + assertThat(this.driver.getWebConnection()).isEqualTo(this.connection); assertThatExceptionOfType(WebDriverException.class).isThrownBy(() -> this.driver.get("https://example.com")); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java index 0a063deea2..4d3f94a152 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java @@ -31,6 +31,8 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; + + /** * Unit tests for * {@link org.springframework.test.web.servlet.result.ModelResultMatchers}. diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/CustomRequestAttributesRequestContextHolderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/CustomRequestAttributesRequestContextHolderTests.java index 9ddaeadcb7..2f27ee4aa9 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/CustomRequestAttributesRequestContextHolderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/CustomRequestAttributesRequestContextHolderTests.java @@ -41,10 +41,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @@ -93,12 +90,12 @@ public class CustomRequestAttributesRequestContextHolderTests { @After public void verifyCustomRequestAttributesAreRestored() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - assertThat(requestAttributes, instanceOf(ServletRequestAttributes.class)); + assertThat(requestAttributes).isInstanceOf(ServletRequestAttributes.class); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); - assertThat(request.getAttribute(FROM_CUSTOM_MOCK), is(FROM_CUSTOM_MOCK)); - assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(nullValue())); - assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(nullValue())); + assertThat(request.getAttribute(FROM_CUSTOM_MOCK)).isEqualTo(FROM_CUSTOM_MOCK); + assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT)).isNull(); + assertThat(request.getAttribute(FROM_MVC_TEST_MOCK)).isNull(); RequestContextHolder.resetRequestAttributes(); this.wac.close(); @@ -128,14 +125,14 @@ public class CustomRequestAttributesRequestContextHolderTests { private static void assertRequestAttributes() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - assertThat(requestAttributes, instanceOf(ServletRequestAttributes.class)); + assertThat(requestAttributes).isInstanceOf(ServletRequestAttributes.class); assertRequestAttributes(((ServletRequestAttributes) requestAttributes).getRequest()); } private static void assertRequestAttributes(ServletRequest request) { - assertThat(request.getAttribute(FROM_CUSTOM_MOCK), is(nullValue())); - assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(FROM_MVC_TEST_DEFAULT)); - assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(FROM_MVC_TEST_MOCK)); + assertThat(request.getAttribute(FROM_CUSTOM_MOCK)).isNull(); + assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT)).isEqualTo(FROM_MVC_TEST_DEFAULT); + assertThat(request.getAttribute(FROM_MVC_TEST_MOCK)).isEqualTo(FROM_MVC_TEST_MOCK); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java index acfa1d6895..c26b1907d8 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java @@ -51,10 +51,7 @@ import org.springframework.web.filter.GenericFilterBean; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -303,7 +300,7 @@ public class RequestContextHolderTests { private static void assertRequestAttributes(boolean withinMockMvc) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - assertThat(requestAttributes, instanceOf(ServletRequestAttributes.class)); + assertThat(requestAttributes).isInstanceOf(ServletRequestAttributes.class); assertRequestAttributes(((ServletRequestAttributes) requestAttributes).getRequest(), withinMockMvc); } @@ -313,18 +310,18 @@ public class RequestContextHolderTests { private static void assertRequestAttributes(ServletRequest request, boolean withinMockMvc) { if (withinMockMvc) { - assertThat(request.getAttribute(FROM_TCF_MOCK), is(nullValue())); - assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(FROM_MVC_TEST_DEFAULT)); - assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(FROM_MVC_TEST_MOCK)); - assertThat(request.getAttribute(FROM_REQUEST_FILTER), is(FROM_REQUEST_FILTER)); - assertThat(request.getAttribute(FROM_REQUEST_ATTRIBUTES_FILTER), is(FROM_REQUEST_ATTRIBUTES_FILTER)); + assertThat(request.getAttribute(FROM_TCF_MOCK)).isNull(); + assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT)).isEqualTo(FROM_MVC_TEST_DEFAULT); + assertThat(request.getAttribute(FROM_MVC_TEST_MOCK)).isEqualTo(FROM_MVC_TEST_MOCK); + assertThat(request.getAttribute(FROM_REQUEST_FILTER)).isEqualTo(FROM_REQUEST_FILTER); + assertThat(request.getAttribute(FROM_REQUEST_ATTRIBUTES_FILTER)).isEqualTo(FROM_REQUEST_ATTRIBUTES_FILTER); } else { - assertThat(request.getAttribute(FROM_TCF_MOCK), is(FROM_TCF_MOCK)); - assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(nullValue())); - assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(nullValue())); - assertThat(request.getAttribute(FROM_REQUEST_FILTER), is(nullValue())); - assertThat(request.getAttribute(FROM_REQUEST_ATTRIBUTES_FILTER), is(nullValue())); + assertThat(request.getAttribute(FROM_TCF_MOCK)).isEqualTo(FROM_TCF_MOCK); + assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT)).isNull(); + assertThat(request.getAttribute(FROM_MVC_TEST_MOCK)).isNull(); + assertThat(request.getAttribute(FROM_REQUEST_FILTER)).isNull(); + assertThat(request.getAttribute(FROM_REQUEST_ATTRIBUTES_FILTER)).isNull(); } } 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 6a32a3afc4..5d3131e09b 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 @@ -35,11 +35,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.request.WebRequest; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/ConditionalDelegatingFilterProxyTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/ConditionalDelegatingFilterProxyTests.java index c58a4f1ba8..3f960bc3cb 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/ConditionalDelegatingFilterProxyTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/ConditionalDelegatingFilterProxyTests.java @@ -31,9 +31,10 @@ import org.springframework.mock.web.MockFilterConfig; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; + + + /** * @author Rob Winch @@ -66,14 +67,14 @@ public class ConditionalDelegatingFilterProxyTests { FilterConfig config = new MockFilterConfig(); filter = new PatternMappingFilterProxy(delegate, "/"); filter.init(config); - assertThat(delegate.filterConfig, is(config)); + assertThat(delegate.filterConfig).isEqualTo(config); } @Test public void destroy() throws Exception { filter = new PatternMappingFilterProxy(delegate, "/"); filter.destroy(); - assertThat(delegate.destroy, is(true)); + assertThat(delegate.destroy).isTrue(); } @Test @@ -235,12 +236,12 @@ public class ConditionalDelegatingFilterProxyTests { filter = new PatternMappingFilterProxy(delegate, pattern); filter.doFilter(request, response, filterChain); - assertThat(delegate.request, equalTo((ServletRequest) null)); - assertThat(delegate.response, equalTo((ServletResponse) null)); - assertThat(delegate.chain, equalTo((FilterChain) null)); + assertThat(delegate.request).isNull(); + assertThat(delegate.response).isNull(); + assertThat(delegate.chain).isNull(); - assertThat(filterChain.getRequest(), equalTo((ServletRequest) request)); - assertThat(filterChain.getResponse(), equalTo((ServletResponse) response)); + assertThat(filterChain.getRequest()).isEqualTo(request); + assertThat(filterChain.getResponse()).isEqualTo(response); filterChain = new MockFilterChain(); } @@ -249,9 +250,9 @@ public class ConditionalDelegatingFilterProxyTests { filter = new PatternMappingFilterProxy(delegate, pattern); filter.doFilter(request, response, filterChain); - assertThat(delegate.request, equalTo((ServletRequest) request)); - assertThat(delegate.response, equalTo((ServletResponse) response)); - assertThat(delegate.chain, equalTo((FilterChain) filterChain)); + assertThat(delegate.request).isEqualTo(request); + assertThat(delegate.response).isEqualTo(response); + assertThat(delegate.chain).isEqualTo(filterChain); delegate = new MockFilter(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java index 48de340027..f68cc8e919 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java @@ -26,8 +26,8 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.beans.CollectingReaderEventListener; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Torsten Juergeleit @@ -50,7 +50,7 @@ public class TxNamespaceHandlerEventTests { @Test public void componentEventReceived() { ComponentDefinition component = this.eventListener.getComponentDefinition("txAdvice"); - assertThat(component, instanceOf(BeanComponentDefinition.class)); + assertThat(component).isInstanceOf(BeanComponentDefinition.class); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java index 0e5778e119..1a4ff2ee89 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java @@ -38,9 +38,8 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.config.TransactionManagementConfigUtils; import org.springframework.transaction.event.TransactionalEventListenerFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -139,14 +138,14 @@ public class EnableTransactionManagementTests { CallCountingTransactionManager txManager = ctx.getBean("qualifiedTransactionManager", CallCountingTransactionManager.class); bean.saveQualifiedFoo(); - assertThat(txManager.begun, equalTo(1)); - assertThat(txManager.commits, equalTo(1)); - assertThat(txManager.rollbacks, equalTo(0)); + assertThat(txManager.begun).isEqualTo(1); + assertThat(txManager.commits).isEqualTo(1); + assertThat(txManager.rollbacks).isEqualTo(0); bean.saveQualifiedFooWithAttributeAlias(); - assertThat(txManager.begun, equalTo(2)); - assertThat(txManager.commits, equalTo(2)); - assertThat(txManager.rollbacks, equalTo(0)); + assertThat(txManager.begun).isEqualTo(2); + assertThat(txManager.commits).isEqualTo(2); + assertThat(txManager.rollbacks).isEqualTo(0); ctx.close(); } @@ -159,9 +158,9 @@ public class EnableTransactionManagementTests { bean.saveFoo(); bean.saveBar(); - assertThat(txManager.begun, equalTo(2)); - assertThat(txManager.commits, equalTo(2)); - assertThat(txManager.rollbacks, equalTo(0)); + assertThat(txManager.begun).isEqualTo(2); + assertThat(txManager.commits).isEqualTo(2); + assertThat(txManager.rollbacks).isEqualTo(0); ctx.close(); } @@ -174,9 +173,9 @@ public class EnableTransactionManagementTests { bean.saveFoo(); bean.saveBar(); - assertThat(txManager.begun, equalTo(2)); - assertThat(txManager.commits, equalTo(2)); - assertThat(txManager.rollbacks, equalTo(0)); + assertThat(txManager.begun).isEqualTo(2); + assertThat(txManager.commits).isEqualTo(2); + assertThat(txManager.rollbacks).isEqualTo(0); ctx.close(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java index 9060b336c0..77ff926038 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java @@ -22,9 +22,8 @@ import org.junit.Test; import org.springframework.beans.FatalBeanException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -61,7 +60,7 @@ public class RollbackRuleTests { public void ancestry() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Exception.class.getName()); // Exception -> Runtime -> NestedRuntime -> MyRuntimeException - assertThat(rr.getDepth(new MyRuntimeException("")), equalTo(3)); + assertThat(rr.getDepth(new MyRuntimeException(""))).isEqualTo(3); } @Test diff --git a/spring-web/spring-web.gradle b/spring-web/spring-web.gradle index 354b65f771..0571c48120 100644 --- a/spring-web/spring-web.gradle +++ b/spring-web/spring-web.gradle @@ -79,6 +79,7 @@ dependencies { testCompile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") testCompile("org.skyscreamer:jsonassert:1.5.0") testCompile("org.xmlunit:xmlunit-matchers:2.6.2") + testCompile("org.xmlunit:xmlunit-assertj:2.6.2") testRuntime("com.sun.mail:javax.mail:1.6.2") testRuntime("com.sun.xml.bind:jaxb-core:2.3.0.1") testRuntime("com.sun.xml.bind:jaxb-impl:2.3.0.1") diff --git a/spring-web/src/test/java/org/springframework/http/CacheControlTests.java b/spring-web/src/test/java/org/springframework/http/CacheControlTests.java index 975ced4ef2..5490ff5460 100644 --- a/spring-web/src/test/java/org/springframework/http/CacheControlTests.java +++ b/spring-web/src/test/java/org/springframework/http/CacheControlTests.java @@ -19,10 +19,10 @@ package org.springframework.http; import java.time.Duration; import java.util.concurrent.TimeUnit; -import org.hamcrest.Matchers; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Brian Clozel @@ -32,73 +32,73 @@ public class CacheControlTests { @Test public void emptyCacheControl() throws Exception { CacheControl cc = CacheControl.empty(); - assertThat(cc.getHeaderValue(), Matchers.nullValue()); + assertThat(cc.getHeaderValue()).isNull(); } @Test public void maxAge() throws Exception { CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600"); } @Test public void maxAge_duration() throws Exception { CacheControl cc = CacheControl.maxAge(Duration.ofHours(1)); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600"); } @Test public void maxAgeAndDirectives() throws Exception { CacheControl cc = CacheControl.maxAge(3600, TimeUnit.SECONDS).cachePublic().noTransform(); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, no-transform, public")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, no-transform, public"); } @Test public void maxAgeAndSMaxAge() throws Exception { CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS).sMaxAge(30, TimeUnit.MINUTES); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, s-maxage=1800")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, s-maxage=1800"); } @Test public void maxAgeAndSMaxAge_duration() throws Exception { CacheControl cc = CacheControl.maxAge(Duration.ofHours(1)).sMaxAge(Duration.ofMinutes(30)); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, s-maxage=1800")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, s-maxage=1800"); } @Test public void noCachePrivate() throws Exception { CacheControl cc = CacheControl.noCache().cachePrivate(); - assertThat(cc.getHeaderValue(), Matchers.equalTo("no-cache, private")); + assertThat(cc.getHeaderValue()).isEqualTo("no-cache, private"); } @Test public void noStore() throws Exception { CacheControl cc = CacheControl.noStore(); - assertThat(cc.getHeaderValue(), Matchers.equalTo("no-store")); + assertThat(cc.getHeaderValue()).isEqualTo("no-store"); } @Test public void staleIfError() throws Exception { CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS).staleIfError(2, TimeUnit.HOURS); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, stale-if-error=7200")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, stale-if-error=7200"); } @Test public void staleIfError_duration() throws Exception { CacheControl cc = CacheControl.maxAge(Duration.ofHours(1)).staleIfError(2, TimeUnit.HOURS); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, stale-if-error=7200")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, stale-if-error=7200"); } @Test public void staleWhileRevalidate() throws Exception { CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS).staleWhileRevalidate(2, TimeUnit.HOURS); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, stale-while-revalidate=7200")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, stale-while-revalidate=7200"); } @Test public void staleWhileRevalidate_duration() throws Exception { CacheControl cc = CacheControl.maxAge(Duration.ofHours(1)).staleWhileRevalidate(2, TimeUnit.HOURS); - assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, stale-while-revalidate=7200")); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, stale-while-revalidate=7200"); } } 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 3d9f6e6ce5..bfcf8ec740 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java @@ -36,13 +36,8 @@ import java.util.TimeZone; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.emptyCollectionOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -67,22 +62,22 @@ public class HttpHeadersTests { public void getOrEmpty() { String key = "FOO"; - assertThat(headers.get(key), is(nullValue())); - assertThat(headers.getOrEmpty(key), is(empty())); + assertThat(headers.get(key)).isNull(); + assertThat(headers.getOrEmpty(key)).isEmpty(); headers.add(key, "bar"); - assertThat(headers.getOrEmpty(key), is(Arrays.asList("bar"))); + assertThat(headers.getOrEmpty(key)).containsExactly("bar"); headers.remove(key); - assertThat(headers.get(key), is(nullValue())); - assertThat(headers.getOrEmpty(key), is(empty())); + assertThat(headers.get(key)).isNull(); + assertThat(headers.getOrEmpty(key)).isEmpty(); } @Test public void getFirst() { headers.add(HttpHeaders.CACHE_CONTROL, "max-age=1000, public"); headers.add(HttpHeaders.CACHE_CONTROL, "s-maxage=1000"); - assertThat(headers.getFirst(HttpHeaders.CACHE_CONTROL), is("max-age=1000, public")); + assertThat(headers.getFirst(HttpHeaders.CACHE_CONTROL)).isEqualTo("max-age=1000, public"); } @Test @@ -223,7 +218,7 @@ public class HttpHeadersTests { headers.add(HttpHeaders.IF_MATCH, "W/\"v2,1\", \"v2,2\""); assertEquals("Invalid If-Match header", "\"v2,0\"", headers.get(HttpHeaders.IF_MATCH).get(0)); assertEquals("Invalid If-Match header", "W/\"v2,1\", \"v2,2\"", headers.get(HttpHeaders.IF_MATCH).get(1)); - assertThat(headers.getIfMatch(), contains("\"v2,0\"", "W/\"v2,1\"", "\"v2,2\"")); + assertThat(headers.getIfMatch()).contains("\"v2,0\"", "W/\"v2,1\"", "\"v2,2\""); } @Test @@ -250,7 +245,7 @@ public class HttpHeadersTests { ifNoneMatchList.add(ifNoneMatch1); ifNoneMatchList.add(ifNoneMatch2); headers.setIfNoneMatch(ifNoneMatchList); - assertThat(headers.getIfNoneMatch(), contains("\"v2.6\"", "\"v2.7\"", "\"v2.8\"")); + assertThat(headers.getIfNoneMatch()).contains("\"v2.6\"", "\"v2.7\"", "\"v2.8\""); assertEquals("Invalid If-None-Match header", "\"v2.6\", \"v2.7\", \"v2.8\"", headers.getFirst("If-None-Match")); } @@ -399,7 +394,7 @@ public class HttpHeadersTests { @Test // SPR-11917 public void getAllowEmptySet() { headers.setAllow(Collections.emptySet()); - assertThat(headers.getAllow(), is(emptyCollectionOf(HttpMethod.class))); + assertThat(headers.getAllow()).isEmpty(); } @Test @@ -414,7 +409,7 @@ public class HttpHeadersTests { @Test public void accessControlAllowHeaders() { List allowedHeaders = headers.getAccessControlAllowHeaders(); - assertThat(allowedHeaders, is(emptyCollectionOf(String.class))); + assertThat(allowedHeaders).isEmpty(); headers.setAccessControlAllowHeaders(Arrays.asList("header1", "header2")); allowedHeaders = headers.getAccessControlAllowHeaders(); assertEquals(allowedHeaders, Arrays.asList("header1", "header2")); @@ -423,7 +418,7 @@ public class HttpHeadersTests { @Test public void accessControlAllowHeadersMultipleValues() { List allowedHeaders = headers.getAccessControlAllowHeaders(); - assertThat(allowedHeaders, is(emptyCollectionOf(String.class))); + assertThat(allowedHeaders).isEmpty(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "header1, header2"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "header3"); allowedHeaders = headers.getAccessControlAllowHeaders(); @@ -433,7 +428,7 @@ public class HttpHeadersTests { @Test public void accessControlAllowMethods() { List allowedMethods = headers.getAccessControlAllowMethods(); - assertThat(allowedMethods, is(emptyCollectionOf(HttpMethod.class))); + assertThat(allowedMethods).isEmpty(); headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET, HttpMethod.POST)); allowedMethods = headers.getAccessControlAllowMethods(); assertEquals(allowedMethods, Arrays.asList(HttpMethod.GET, HttpMethod.POST)); @@ -449,7 +444,7 @@ public class HttpHeadersTests { @Test public void accessControlExposeHeaders() { List exposedHeaders = headers.getAccessControlExposeHeaders(); - assertThat(exposedHeaders, is(emptyCollectionOf(String.class))); + assertThat(exposedHeaders).isEmpty(); headers.setAccessControlExposeHeaders(Arrays.asList("header1", "header2")); exposedHeaders = headers.getAccessControlExposeHeaders(); assertEquals(exposedHeaders, Arrays.asList("header1", "header2")); @@ -465,7 +460,7 @@ public class HttpHeadersTests { @Test public void accessControlRequestHeaders() { List requestHeaders = headers.getAccessControlRequestHeaders(); - assertThat(requestHeaders, is(emptyCollectionOf(String.class))); + assertThat(requestHeaders).isEmpty(); headers.setAccessControlRequestHeaders(Arrays.asList("header1", "header2")); requestHeaders = headers.getAccessControlRequestHeaders(); assertEquals(requestHeaders, Arrays.asList("header1", "header2")); @@ -520,20 +515,20 @@ public class HttpHeadersTests { @Test public void firstDate() { headers.setDate(HttpHeaders.DATE, 1496370120000L); - assertThat(headers.getFirstDate(HttpHeaders.DATE), is(1496370120000L)); + assertThat(headers.getFirstDate(HttpHeaders.DATE)).isEqualTo(1496370120000L); headers.clear(); headers.add(HttpHeaders.DATE, "Fri, 02 Jun 2017 02:22:00 GMT"); headers.add(HttpHeaders.DATE, "Sat, 18 Dec 2010 10:20:00 GMT"); - assertThat(headers.getFirstDate(HttpHeaders.DATE), is(1496370120000L)); + assertThat(headers.getFirstDate(HttpHeaders.DATE)).isEqualTo(1496370120000L); } @Test public void firstZonedDateTime() { ZonedDateTime date = ZonedDateTime.of(2017, 6, 2, 2, 22, 0, 0, ZoneId.of("GMT")); headers.setZonedDateTime(HttpHeaders.DATE, date); - assertThat(headers.getFirst(HttpHeaders.DATE), is("Fri, 02 Jun 2017 02:22:00 GMT")); + assertThat(headers.getFirst(HttpHeaders.DATE)).isEqualTo("Fri, 02 Jun 2017 02:22:00 GMT"); assertTrue(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)); headers.clear(); diff --git a/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java b/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java index c8db115c9a..4a8d7b7022 100644 --- a/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java +++ b/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java @@ -20,10 +20,7 @@ import java.time.Duration; import org.junit.Test; -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.CoreMatchers.endsWith; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -51,13 +48,13 @@ public class ResponseCookieTests { String expires = HttpHeaders.formatDate(System.currentTimeMillis() + maxAge.toMillis()); expires = expires.substring(0, expires.indexOf(":") + 1); - assertThat(ResponseCookie.from("id", "1fWa").maxAge(maxAge).build().toString(), allOf( - startsWith("id=1fWa; Max-Age=31536000; Expires=" + expires), - endsWith(" GMT"))); + assertThat(ResponseCookie.from("id", "1fWa").maxAge(maxAge).build().toString()) + .startsWith("id=1fWa; Max-Age=31536000; Expires=" + expires) + .endsWith(" GMT"); - assertThat(ResponseCookie.from("id", "1fWa").maxAge(maxAge.getSeconds()).build().toString(), allOf( - startsWith("id=1fWa; Max-Age=31536000; Expires=" + expires), - endsWith(" GMT"))); + assertThat(ResponseCookie.from("id", "1fWa").maxAge(maxAge.getSeconds()).build().toString()) + .startsWith("id=1fWa; Max-Age=31536000; Expires=" + expires) + .endsWith(" GMT"); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java b/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java index 1dc47e8427..905fcd5d70 100644 --- a/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java +++ b/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java @@ -22,10 +22,9 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; -import org.hamcrest.Matchers; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -265,8 +264,8 @@ public class ResponseEntityTests { assertTrue(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)); assertEquals(entity, responseEntity.getBody()); String cacheControlHeader = responseEntity.getHeaders().getCacheControl(); - assertThat(cacheControlHeader, - Matchers.equalTo("max-age=3600, must-revalidate, private, proxy-revalidate, s-maxage=1800")); + assertThat(cacheControlHeader).isEqualTo( + "max-age=3600, must-revalidate, private, proxy-revalidate, s-maxage=1800"); } @Test @@ -284,7 +283,7 @@ public class ResponseEntityTests { assertEquals(entity, responseEntity.getBody()); String cacheControlHeader = responseEntity.getHeaders().getCacheControl(); - assertThat(cacheControlHeader, Matchers.equalTo("no-store")); + assertThat(cacheControlHeader).isEqualTo("no-store"); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractMockWebServerTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractMockWebServerTestCase.java index 9a09bdf40a..0139b734f8 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractMockWebServerTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractMockWebServerTestCase.java @@ -22,14 +22,14 @@ import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Brian Clozel @@ -64,8 +64,8 @@ public class AbstractMockWebServerTestCase { public MockResponse dispatch(RecordedRequest request) throws InterruptedException { try { if (request.getPath().equals("/echo")) { - assertThat(request.getHeader("Host"), - Matchers.containsString("localhost:" + port)); + assertThat(request.getHeader("Host")) + .contains("localhost:" + port); MockResponse response = new MockResponse() .setHeaders(request.getHeaders()) .setHeader("Content-Length", request.getBody().size()) @@ -81,26 +81,25 @@ public class AbstractMockWebServerTestCase { return new MockResponse().setResponseCode(404); } else if(request.getPath().startsWith("/params")) { - assertThat(request.getPath(), Matchers.containsString("param1=value")); - assertThat(request.getPath(), Matchers.containsString("param2=value1¶m2=value2")); + assertThat(request.getPath()).contains("param1=value"); + assertThat(request.getPath()).contains("param2=value1¶m2=value2"); return new MockResponse(); } else if(request.getPath().equals("/methods/post")) { - assertThat(request.getMethod(), Matchers.is("POST")); + assertThat(request.getMethod()).isEqualTo("POST"); String transferEncoding = request.getHeader("Transfer-Encoding"); if(StringUtils.hasLength(transferEncoding)) { - assertThat(transferEncoding, Matchers.is("chunked")); + assertThat(transferEncoding).isEqualTo("chunked"); } else { long contentLength = Long.parseLong(request.getHeader("Content-Length")); - assertThat("Invalid content-length", - request.getBody().size(), Matchers.is(contentLength)); + assertThat(request.getBody().size()).isEqualTo(contentLength); } return new MockResponse().setResponseCode(200); } else if(request.getPath().startsWith("/methods/")) { String expectedMethod = request.getPath().replace("/methods/","").toUpperCase(); - assertThat(request.getMethod(), Matchers.is(expectedMethod)); + assertThat(request.getMethod()).isEqualTo(expectedMethod); return new MockResponse(); } return new MockResponse().setResponseCode(404); diff --git a/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java b/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java index 6f31f3a00f..9a3ef80f48 100644 --- a/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java @@ -26,8 +26,7 @@ import org.junit.Test; import org.springframework.util.StreamUtils; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -54,7 +53,7 @@ public class SimpleClientHttpResponseTests { given(this.connection.getInputStream()).willReturn(is); InputStream responseStream = this.response.getBody(); - assertThat(StreamUtils.copyToString(responseStream, StandardCharsets.UTF_8), is("Spring")); + assertThat(StreamUtils.copyToString(responseStream, StandardCharsets.UTF_8)).isEqualTo("Spring"); this.response.close(); assertTrue(is.isClosed()); @@ -70,11 +69,11 @@ public class SimpleClientHttpResponseTests { InputStream responseStream = this.response.getBody(); responseStream.read(buf); - assertThat(new String(buf, StandardCharsets.UTF_8), is("Spring")); - assertThat(is.available(), is(6)); + assertThat(new String(buf, StandardCharsets.UTF_8)).isEqualTo("Spring"); + assertThat(is.available()).isEqualTo(6); this.response.close(); - assertThat(is.available(), is(0)); + assertThat(is.available()).isEqualTo(0); assertTrue(is.isClosed()); verify(this.connection, never()).disconnect(); } @@ -87,11 +86,11 @@ public class SimpleClientHttpResponseTests { InputStream responseStream = this.response.getBody(); responseStream.read(buf); - assertThat(new String(buf, StandardCharsets.UTF_8), is("Spring")); - assertThat(is.available(), is(6)); + assertThat(new String(buf, StandardCharsets.UTF_8)).isEqualTo("Spring"); + assertThat(is.available()).isEqualTo(6); this.response.close(); - assertThat(is.available(), is(0)); + assertThat(is.available()).isEqualTo(0); assertTrue(is.isClosed()); verify(this.connection, never()).disconnect(); } @@ -117,7 +116,7 @@ public class SimpleClientHttpResponseTests { given(this.connection.getInputStream()).willReturn(is); this.response.close(); - assertThat(is.available(), is(0)); + assertThat(is.available()).isEqualTo(0); assertTrue(is.isClosed()); verify(this.connection, never()).disconnect(); } diff --git a/spring-web/src/test/java/org/springframework/http/client/support/InterceptingHttpAccessorTests.java b/spring-web/src/test/java/org/springframework/http/client/support/InterceptingHttpAccessorTests.java index 316a07032e..ca621af0f7 100644 --- a/spring-web/src/test/java/org/springframework/http/client/support/InterceptingHttpAccessorTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/support/InterceptingHttpAccessorTests.java @@ -19,7 +19,6 @@ package org.springframework.http.client.support; import java.util.Arrays; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.core.Ordered; @@ -29,7 +28,8 @@ import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests for {@link InterceptingHttpAccessor}. @@ -49,9 +49,9 @@ public class InterceptingHttpAccessorTests { ); accessor.setInterceptors(interceptors); - assertThat(accessor.getInterceptors().get(0), Matchers.instanceOf(FirstClientHttpRequestInterceptor.class)); - assertThat(accessor.getInterceptors().get(1), Matchers.instanceOf(SecondClientHttpRequestInterceptor.class)); - assertThat(accessor.getInterceptors().get(2), Matchers.instanceOf(ThirdClientHttpRequestInterceptor.class)); + assertThat(accessor.getInterceptors().get(0)).isInstanceOf(FirstClientHttpRequestInterceptor.class); + assertThat(accessor.getInterceptors().get(1)).isInstanceOf(SecondClientHttpRequestInterceptor.class); + assertThat(accessor.getInterceptors().get(2)).isInstanceOf(ThirdClientHttpRequestInterceptor.class); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java index c3bf8c549a..df85d49cea 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java @@ -18,6 +18,7 @@ package org.springframework.http.codec; import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.List; import java.util.Map; import org.junit.Test; @@ -34,10 +35,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.startsWith; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.springframework.http.MediaType.TEXT_PLAIN; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; @@ -62,9 +60,10 @@ public class ResourceHttpMessageWriterTests { @Test + @SuppressWarnings({ "unchecked", "rawtypes" }) public void getWritableMediaTypes() throws Exception { - assertThat(this.writer.getWritableMediaTypes(), - containsInAnyOrder(MimeTypeUtils.APPLICATION_OCTET_STREAM, MimeTypeUtils.ALL)); + assertThat((List) this.writer.getWritableMediaTypes()) + .containsExactlyInAnyOrder(MimeTypeUtils.APPLICATION_OCTET_STREAM, MimeTypeUtils.ALL); } @Test @@ -72,9 +71,9 @@ public class ResourceHttpMessageWriterTests { testWrite(get("/").build()); - assertThat(this.response.getHeaders().getContentType(), is(TEXT_PLAIN)); - assertThat(this.response.getHeaders().getContentLength(), is(39L)); - assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES), is("bytes")); + assertThat(this.response.getHeaders().getContentType()).isEqualTo(TEXT_PLAIN); + assertThat(this.response.getHeaders().getContentLength()).isEqualTo(39L); + assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); String content = "Spring Framework test resource content."; StepVerifier.create(this.response.getBodyAsString()).expectNext(content).expectComplete().verify(); @@ -85,9 +84,9 @@ public class ResourceHttpMessageWriterTests { testWrite(get("/").range(of(0, 5)).build()); - assertThat(this.response.getHeaders().getContentType(), is(TEXT_PLAIN)); - assertThat(this.response.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE), is("bytes 0-5/39")); - assertThat(this.response.getHeaders().getContentLength(), is(6L)); + assertThat(this.response.getHeaders().getContentType()).isEqualTo(TEXT_PLAIN); + assertThat(this.response.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE)).isEqualTo("bytes 0-5/39"); + assertThat(this.response.getHeaders().getContentLength()).isEqualTo(6L); StepVerifier.create(this.response.getBodyAsString()).expectNext("Spring").expectComplete().verify(); } @@ -101,7 +100,7 @@ public class ResourceHttpMessageWriterTests { String contentType = headers.getContentType().toString(); String boundary = contentType.substring(30); - assertThat(contentType, startsWith("multipart/byteranges;boundary=")); + assertThat(contentType).startsWith("multipart/byteranges;boundary="); StepVerifier.create(this.response.getBodyAsString()) .consumeNextWith(content -> { @@ -136,8 +135,8 @@ public class ResourceHttpMessageWriterTests { testWrite(get("/").header(HttpHeaders.RANGE, "invalid").build()); - assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES), is("bytes")); - assertThat(this.response.getStatusCode(), is(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)); + assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); + assertThat(this.response.getStatusCode()).isEqualTo(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java index f49e609401..9f241c0904 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java @@ -32,13 +32,13 @@ import org.springframework.core.codec.AbstractEncoderTestCase; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.MediaType; import org.springframework.http.codec.Pojo; +import org.springframework.tests.XmlContent; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.springframework.core.io.buffer.DataBufferUtils.release; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Sebastien Deleuze @@ -109,7 +109,7 @@ public class Jaxb2XmlEncoderTests extends AbstractEncoderTestCasefoo // But on CI server we get: foo // So... we make a compromise: - assertThat(item.getString(), - allOf(startsWith("foo"))); + assertThat(item.getString()) + .startsWith("foo"); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java index a3c17afff6..c9a439f274 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java @@ -33,10 +33,8 @@ import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.util.FileCopyUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -73,7 +71,7 @@ public class ResourceHttpMessageConverterTests { inputMessage.getHeaders().setContentDisposition( ContentDisposition.builder("attachment").filename("yourlogo.jpg").build()); Resource actualResource = converter.read(Resource.class, inputMessage); - assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream()), is(body)); + assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream())).isEqualTo(body); assertEquals("yourlogo.jpg", actualResource.getFilename()); } @@ -85,8 +83,8 @@ public class ResourceHttpMessageConverterTests { inputMessage.getHeaders().setContentDisposition( ContentDisposition.builder("attachment").filename("yourlogo.jpg").build()); Resource actualResource = converter.read(InputStreamResource.class, inputMessage); - assertThat(actualResource, instanceOf(InputStreamResource.class)); - assertThat(actualResource.getInputStream(), is(body)); + assertThat(actualResource).isInstanceOf(InputStreamResource.class); + assertThat(actualResource.getInputStream()).isEqualTo(body); assertEquals("yourlogo.jpg", actualResource.getFilename()); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java index 948d0665c5..7a0604c13d 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.BDDMockito; import org.mockito.Mockito; @@ -38,8 +37,7 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpOutputMessage; import org.springframework.util.StringUtils; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -87,11 +85,11 @@ public class ResourceRegionHttpMessageConverterTests { converter.write(region, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); - assertThat(headers.getContentType(), is(MediaType.TEXT_PLAIN)); - assertThat(headers.getContentLength(), is(6L)); - assertThat(headers.get(HttpHeaders.CONTENT_RANGE).size(), is(1)); - assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0), is("bytes 0-5/39")); - assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Spring")); + assertThat(headers.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(headers.getContentLength()).isEqualTo(6L); + assertThat(headers.get(HttpHeaders.CONTENT_RANGE)).hasSize(1); + assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0)).isEqualTo("bytes 0-5/39"); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo("Spring"); } @Test @@ -102,11 +100,11 @@ public class ResourceRegionHttpMessageConverterTests { converter.write(region, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); - assertThat(headers.getContentType(), is(MediaType.TEXT_PLAIN)); - assertThat(headers.getContentLength(), is(32L)); - assertThat(headers.get(HttpHeaders.CONTENT_RANGE).size(), is(1)); - assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0), is("bytes 7-38/39")); - assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Framework test resource content.")); + assertThat(headers.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(headers.getContentLength()).isEqualTo(32L); + assertThat(headers.get(HttpHeaders.CONTENT_RANGE)).hasSize(1); + assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0)).isEqualTo("bytes 7-38/39"); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo("Framework test resource content."); } @Test @@ -122,30 +120,30 @@ public class ResourceRegionHttpMessageConverterTests { converter.write(regions, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); - assertThat(headers.getContentType().toString(), Matchers.startsWith("multipart/byteranges;boundary=")); + assertThat(headers.getContentType().toString()).startsWith("multipart/byteranges;boundary="); String boundary = "--" + headers.getContentType().toString().substring(30); String content = outputMessage.getBodyAsString(StandardCharsets.UTF_8); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); - assertThat(ranges[0], is(boundary)); - assertThat(ranges[1], is("Content-Type: text/plain")); - assertThat(ranges[2], is("Content-Range: bytes 0-5/39")); - assertThat(ranges[3], is("Spring")); + assertThat(ranges[0]).isEqualTo(boundary); + assertThat(ranges[1]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[2]).isEqualTo("Content-Range: bytes 0-5/39"); + assertThat(ranges[3]).isEqualTo("Spring"); - assertThat(ranges[4], is(boundary)); - assertThat(ranges[5], is("Content-Type: text/plain")); - assertThat(ranges[6], is("Content-Range: bytes 7-15/39")); - assertThat(ranges[7], is("Framework")); + assertThat(ranges[4]).isEqualTo(boundary); + assertThat(ranges[5]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[6]).isEqualTo("Content-Range: bytes 7-15/39"); + assertThat(ranges[7]).isEqualTo("Framework"); - assertThat(ranges[8], is(boundary)); - assertThat(ranges[9], is("Content-Type: text/plain")); - assertThat(ranges[10], is("Content-Range: bytes 17-20/39")); - assertThat(ranges[11], is("test")); + assertThat(ranges[8]).isEqualTo(boundary); + assertThat(ranges[9]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[10]).isEqualTo("Content-Range: bytes 17-20/39"); + assertThat(ranges[11]).isEqualTo("test"); - assertThat(ranges[12], is(boundary)); - assertThat(ranges[13], is("Content-Type: text/plain")); - assertThat(ranges[14], is("Content-Range: bytes 22-38/39")); - assertThat(ranges[15], is("resource content.")); + assertThat(ranges[12]).isEqualTo(boundary); + assertThat(ranges[13]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[14]).isEqualTo("Content-Range: bytes 22-38/39"); + assertThat(ranges[15]).isEqualTo("resource content."); } @Test // SPR-15041 @@ -160,9 +158,9 @@ public class ResourceRegionHttpMessageConverterTests { converter.write(Collections.singletonList(resourceRegion), null, outputMessage); - assertThat(outputMessage.getHeaders().getContentType(), is(MediaType.APPLICATION_OCTET_STREAM)); - assertThat(outputMessage.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE), is("bytes 0-5/12")); - assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Spring")); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_OCTET_STREAM); + assertThat(outputMessage.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE)).isEqualTo("bytes 0-5/12"); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo("Spring"); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java index e85866435a..5fe703ec99 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java @@ -35,11 +35,11 @@ import org.xmlunit.diff.NodeMatcher; import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; +import org.springframework.tests.XmlContent; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -114,8 +114,8 @@ public class AtomFeedHttpMessageConverterTests { "id1title1" + "id2title2"; NodeMatcher nm = new DefaultNodeMatcher(ElementSelectors.byName); - assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo(expected).ignoreWhitespace().withNodeMatcher(nm)); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarToIgnoringWhitespace(expected, nm); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java index 15f9e7782b..689103c70f 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java @@ -28,13 +28,13 @@ import com.rometools.rome.feed.rss.Item; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; -import org.xmlunit.matchers.CompareMatcher; import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; +import org.springframework.tests.XmlContent; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -112,7 +112,8 @@ public class RssChannelHttpMessageConverterTests { "title1" + "title2" + ""; - assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), isSimilarTo(expected)); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarToIgnoringWhitespace(expected); } @Test @@ -135,8 +136,4 @@ public class RssChannelHttpMessageConverterTests { outputMessage.getHeaders().getContentType()); } - private static CompareMatcher isSimilarTo(final String content) { - return CompareMatcher.isSimilarTo(content) - .ignoreWhitespace(); - } } 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 05988bc474..ef0f0cf4f7 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 @@ -83,11 +83,9 @@ import org.junit.Test; import org.springframework.beans.FatalBeanException; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -295,7 +293,7 @@ public class Jackson2ObjectMapperBuilderTests { .build(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); - assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid")); + assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @Test // SPR-12634 @@ -308,7 +306,7 @@ public class Jackson2ObjectMapperBuilderTests { .build(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); - assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid")); + assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @Test // SPR-12634 @@ -319,7 +317,7 @@ public class Jackson2ObjectMapperBuilderTests { .serializerByType(Integer.class, new CustomIntegerSerializer()).build(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); - assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid")); + assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @Test // gh-22576 @@ -427,16 +425,16 @@ public class Jackson2ObjectMapperBuilderTests { .filters(new SimpleFilterProvider().setFailOnUnknownId(false)).build(); JacksonFilteredBean bean = new JacksonFilteredBean("value1", "value2"); String output = objectMapper.writeValueAsString(bean); - assertThat(output, containsString("value1")); - assertThat(output, containsString("value2")); + assertThat(output).contains("value1"); + assertThat(output).contains("value2"); SimpleFilterProvider provider = new SimpleFilterProvider() .setFailOnUnknownId(false) .setDefaultFilter(SimpleBeanPropertyFilter.serializeAllExcept("property2")); objectMapper = Jackson2ObjectMapperBuilder.json().filters(provider).build(); output = objectMapper.writeValueAsString(bean); - assertThat(output, containsString("value1")); - assertThat(output, not(containsString("value2"))); + assertThat(output).contains("value1"); + assertThat(output).doesNotContain("value2"); } @Test @@ -529,7 +527,7 @@ public class Jackson2ObjectMapperBuilderTests { assertEquals(XmlMapper.class, objectMapper.getClass()); ListContainer container = new ListContainer<>(Arrays.asList("foo", "bar")); String output = objectMapper.writeValueAsString(container); - assertThat(output, containsString("foobar")); + assertThat(output).contains("foobar"); } @Test // SPR-14435 @@ -562,9 +560,9 @@ public class Jackson2ObjectMapperBuilderTests { .build(); String json = objectMapper.writeValueAsString(new JacksonVisibilityBean()); - assertThat(json, containsString("property1")); - assertThat(json, containsString("property2")); - assertThat(json, not(containsString("property3"))); + assertThat(json).contains("property1"); + assertThat(json).contains("property2"); + assertThat(json).doesNotContain("property3"); } public static class CustomIntegerModule extends Module { diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java index 7f7ca552b5..a4b2d55766 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java @@ -64,9 +64,8 @@ import org.junit.Test; import org.springframework.beans.FatalBeanException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -228,7 +227,7 @@ public class Jackson2ObjectMapperFactoryBeanTests { DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); - assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid")); + assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @Test // SPR-12634 @@ -242,7 +241,7 @@ public class Jackson2ObjectMapperFactoryBeanTests { DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); - assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid")); + assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @Test @@ -301,8 +300,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { JacksonFilteredBean bean = new JacksonFilteredBean("value1", "value2"); String output = objectMapper.writeValueAsString(bean); - assertThat(output, containsString("value1")); - assertThat(output, containsString("value2")); + assertThat(output).contains("value1"); + assertThat(output).contains("value2"); } @Test 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 8427f2739c..9aca2bef94 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 @@ -42,10 +42,8 @@ import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.lang.Nullable; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -359,9 +357,9 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(jacksonValue, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result, containsString("\"withView1\":\"with\"")); - assertThat(result, not(containsString("\"withView2\":\"with\""))); - assertThat(result, not(containsString("\"withoutView\":\"without\""))); + assertThat(result).contains("\"withView1\":\"with\""); + assertThat(result).doesNotContain("\"withView2\":\"with\""); + assertThat(result).doesNotContain("\"withoutView\":\"without\""); } @Test @@ -377,9 +375,9 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(jacksonValue, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result, not(containsString("\"withView1\":\"with\""))); - assertThat(result, not(containsString("\"withView2\":\"with\""))); - assertThat(result, containsString("\"withoutView\":\"without\"")); + assertThat(result).doesNotContain("\"withView1\":\"with\""); + assertThat(result).doesNotContain("\"withView2\":\"with\""); + assertThat(result).contains("\"withoutView\":\"without\""); } @Test @@ -396,8 +394,8 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(jacksonValue, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result, containsString("\"property1\":\"value\"")); - assertThat(result, not(containsString("\"property2\":\"value\""))); + assertThat(result).contains("\"property1\":\"value\""); + assertThat(result).doesNotContain("\"property2\":\"value\""); } @Test // SPR-13318 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 22a00da7b4..6a7e304977 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 @@ -39,9 +39,10 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.tests.XmlContent; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -49,7 +50,6 @@ import static org.xmlunit.diff.ComparisonType.XML_STANDALONE; import static org.xmlunit.diff.DifferenceEvaluators.Default; import static org.xmlunit.diff.DifferenceEvaluators.chain; import static org.xmlunit.diff.DifferenceEvaluators.downgradeDifferencesToEqual; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * Tests for {@link Jaxb2RootElementHttpMessageConverter}. @@ -183,8 +183,8 @@ public class Jaxb2RootElementHttpMessageConverterTests { assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); - assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo("").withDifferenceEvaluator(ev)); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarTo("", ev); } @Test @@ -194,8 +194,8 @@ public class Jaxb2RootElementHttpMessageConverterTests { assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); - assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo("").withDifferenceEvaluator(ev)); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarTo("", ev); } // SPR-11488 @@ -206,8 +206,8 @@ public class Jaxb2RootElementHttpMessageConverterTests { MyJaxb2RootElementHttpMessageConverter myConverter = new MyJaxb2RootElementHttpMessageConverter(); myConverter.write(new MyRootElement(new MyCustomElement("a", "b")), null, outputMessage); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); - assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo("a|||b").withDifferenceEvaluator(ev)); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarTo("a|||b", ev); } @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 c860bd9742..88d9000618 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 @@ -30,10 +30,8 @@ import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.json.MappingJacksonValue; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -137,9 +135,9 @@ public class MappingJackson2XmlHttpMessageConverterTests { this.converter.write(jacksonValue, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result, containsString("with")); - assertThat(result, not(containsString("with"))); - assertThat(result, not(containsString("without"))); + assertThat(result).contains("with"); + assertThat(result).doesNotContain("with"); + assertThat(result).doesNotContain("without"); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java index 12d6592826..3bfce9c5fb 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java @@ -44,14 +44,14 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.tests.XmlContent; import org.springframework.util.FileCopyUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -143,7 +143,7 @@ public class SourceHttpMessageConverterTests { SAXSource result = (SAXSource) converter.read(SAXSource.class, inputMessage); InputSource inputSource = result.getInputSource(); String s = FileCopyUtils.copyToString(new InputStreamReader(inputSource.getByteStream())); - assertThat("Invalid result", s, isSimilarTo(BODY)); + assertThat(XmlContent.from(s)).isSimilarTo(BODY); } @Test @@ -270,7 +270,7 @@ public class SourceHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "xml")); StreamSource result = (StreamSource) converter.read(StreamSource.class, inputMessage); String s = FileCopyUtils.copyToString(new InputStreamReader(result.getInputStream())); - assertThat("Invalid result", s, isSimilarTo(BODY)); + assertThat(XmlContent.of(s)).isSimilarTo(BODY); } @Test @@ -292,8 +292,8 @@ public class SourceHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(domSource, null, outputMessage); - assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo("Hello World")); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarTo("Hello World"); assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length, @@ -307,8 +307,8 @@ public class SourceHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(saxSource, null, outputMessage); - assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo("Hello World")); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarTo("Hello World"); assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); } @@ -320,8 +320,8 @@ public class SourceHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(streamSource, null, outputMessage); - assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8), - isSimilarTo("Hello World")); + assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) + .isSimilarTo("Hello World"); assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java index 7988d3d042..d9b1644325 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java @@ -19,7 +19,6 @@ package org.springframework.http.server.reactive; import java.net.URI; import java.time.Duration; -import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; import reactor.core.publisher.Flux; @@ -33,7 +32,8 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Stephane Maldini @@ -58,7 +58,7 @@ public class AsyncIntegrationTests extends AbstractHttpHandlerIntegrationTests { ResponseEntity response = new RestTemplate().exchange( RequestEntity.get(url).build(), String.class); - assertThat(response.getBody(), Matchers.equalTo("hello")); + assertThat(response.getBody()).isEqualTo("hello"); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java index 6734822177..2583df3f44 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java @@ -32,10 +32,7 @@ import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -75,11 +72,14 @@ public class CookieIntegrationTests extends AbstractHttpHandlerIntegrationTests List headerValues = response.getHeaders().get("Set-Cookie"); assertEquals(2, headerValues.size()); - assertThat(splitCookie(headerValues.get(0)), containsInAnyOrder(equalTo("SID=31d4d96e407aad42"), - equalToIgnoringCase("Path=/"), equalToIgnoringCase("Secure"), equalToIgnoringCase("HttpOnly"))); - - assertThat(splitCookie(headerValues.get(1)), containsInAnyOrder(equalTo("lang=en-US"), - equalToIgnoringCase("Path=/"), equalToIgnoringCase("Domain=example.com"))); + List cookie0 = splitCookie(headerValues.get(0)); + assertThat(cookie0.remove("SID=31d4d96e407aad42")).as("SID").isTrue(); + assertThat(cookie0.stream().map(String::toLowerCase)) + .containsExactlyInAnyOrder("path=/", "secure", "httponly"); + List cookie1 = splitCookie(headerValues.get(1)); + assertThat(cookie1.remove("lang=en-US")).as("lang").isTrue(); + assertThat(cookie1.stream().map(String::toLowerCase)) + .containsExactlyInAnyOrder("path=/", "domain=example.com"); } // No client side HttpCookie support yet 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 c80b0c8b6c..cc20b1f0b6 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 @@ -36,9 +36,7 @@ import org.springframework.web.bind.ServletRequestParameterPropertyValues; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.multipart.support.StringMultipartFileEditor; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -149,14 +147,9 @@ public class WebRequestDataBinderTests { request.addParameter("_someMap", "visible"); binder.bind(new ServletWebRequest(request)); - assertThat(target.getSomeSet(), notNullValue()); - assertThat(target.getSomeSet(), isA(Set.class)); - - assertThat(target.getSomeList(), notNullValue()); - assertThat(target.getSomeList(), isA(List.class)); - - assertThat(target.getSomeMap(), notNullValue()); - assertThat(target.getSomeMap(), isA(Map.class)); + assertThat(target.getSomeSet()).isNotNull().isInstanceOf(Set.class); + assertThat(target.getSomeList()).isNotNull().isInstanceOf(List.class); + assertThat(target.getSomeMap()).isNotNull().isInstanceOf(Map.class); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java b/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java index 7dbb6f7678..b22129ed37 100644 --- a/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java +++ b/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java @@ -26,13 +26,12 @@ import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import okio.Buffer; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.springframework.http.MediaType; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -170,9 +169,9 @@ public class AbstractMockWebServerTestCase { private MockResponse formRequest(RecordedRequest request) { assertEquals("application/x-www-form-urlencoded;charset=UTF-8", request.getHeader("Content-Type")); String body = request.getBody().readUtf8(); - assertThat(body, Matchers.containsString("name+1=value+1")); - assertThat(body, Matchers.containsString("name+2=value+2%2B1")); - assertThat(body, Matchers.containsString("name+2=value+2%2B2")); + assertThat(body).contains("name+1=value+1"); + assertThat(body).contains("name+2=value+2%2B1"); + assertThat(body).contains("name+2=value+2%2B2"); return new MockResponse().setResponseCode(200); } diff --git a/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java b/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java index 0a54dd3607..466a8a3767 100644 --- a/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java @@ -27,8 +27,7 @@ import org.junit.Test; import org.springframework.http.HttpStatus; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -52,7 +51,7 @@ public class HttpStatusCodeExceptionTests { ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); HttpStatusCodeException ex2 = (HttpStatusCodeException) new ObjectInputStream(in).readObject(); - assertThat(ex2.getResponseBodyAsString(), equalTo(ex1.getResponseBodyAsString())); + assertThat(ex2.getResponseBodyAsString()).isEqualTo(ex1.getResponseBodyAsString()); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java b/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java index daf79db000..e44334a7d0 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java @@ -47,9 +47,8 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.StreamUtils; import org.springframework.web.util.DefaultUriBuilderFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -634,7 +633,7 @@ public class RestTemplateTests { entityHeaders.add("MyHeader", "MyEntityValue"); HttpEntity entity = new HttpEntity<>(null, entityHeaders); template.exchange("https://example.com", POST, entity, Void.class); - assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue")); + assertThat(requestHeaders.get("MyHeader")).contains("MyEntityValue", "MyInterceptorValue"); verify(response).close(); } @@ -658,7 +657,7 @@ public class RestTemplateTests { entityHeaders.add("MyHeader", "MyEntityValue"); HttpEntity entity = new HttpEntity<>("Hello World", entityHeaders); template.exchange("https://example.com", POST, entity, Void.class); - assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue")); + assertThat(requestHeaders.get("MyHeader")).contains("MyEntityValue", "MyInterceptorValue"); verify(response).close(); } diff --git a/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java b/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java index 6a1fbf5808..58b7e86c5e 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java @@ -24,8 +24,7 @@ import org.springframework.context.annotation.AnnotationBeanNameGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; /** @@ -80,7 +79,7 @@ public class AnnotationConfigWebApplicationContextTests { }); ctx.setConfigLocation(Config.class.getName()); ctx.refresh(); - assertThat(ctx.containsBean("custom-myConfig"), is(true)); + assertThat(ctx.containsBean("custom-myConfig")).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/web/context/support/StandardServletEnvironmentTests.java b/spring-web/src/test/java/org/springframework/web/context/support/StandardServletEnvironmentTests.java index b0f263c04a..683a63cf20 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/StandardServletEnvironmentTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/StandardServletEnvironmentTests.java @@ -24,9 +24,8 @@ import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for {@link StandardServletEnvironment}. @@ -44,16 +43,16 @@ public class StandardServletEnvironmentTests { MutablePropertySources sources = env.getPropertySources(); assertThat(sources.precedenceOf(PropertySource.named( - StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), equalTo(0)); + StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME))).isEqualTo(0); assertThat(sources.precedenceOf(PropertySource.named( - StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), equalTo(1)); + StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME))).isEqualTo(1); assertThat(sources.precedenceOf(PropertySource.named( - StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)), equalTo(2)); + StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME))).isEqualTo(2); assertThat(sources.precedenceOf(PropertySource.named( - StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(3)); + StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))).isEqualTo(3); assertThat(sources.precedenceOf(PropertySource.named( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4)); - assertThat(sources.size(), is(5)); + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))).isEqualTo(4); + assertThat(sources).hasSize(5); } } 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 089c4503e0..19d6a57ceb 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 @@ -26,8 +26,7 @@ import org.springframework.http.HttpMethod; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -67,8 +66,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -79,8 +78,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -91,8 +90,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); } @@ -117,8 +116,8 @@ public class DefaultCorsProcessorTests { assertEquals("*", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -136,8 +135,8 @@ public class DefaultCorsProcessorTests { assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -153,8 +152,8 @@ public class DefaultCorsProcessorTests { assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -166,8 +165,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -185,8 +184,8 @@ public class DefaultCorsProcessorTests { assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1")); assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2")); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -198,8 +197,8 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("*"); this.processor.processRequest(this.conf, this.request, this.response); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -211,8 +210,8 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("*"); this.processor.processRequest(this.conf, this.request, this.response); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); } @@ -226,8 +225,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); assertEquals("GET,HEAD", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); } @Test @@ -237,8 +236,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); } @@ -250,8 +249,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); } @@ -264,8 +263,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); } @@ -287,8 +286,8 @@ public class DefaultCorsProcessorTests { assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); assertEquals("GET,PUT", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -309,8 +308,8 @@ public class DefaultCorsProcessorTests { assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -329,8 +328,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -351,8 +350,8 @@ public class DefaultCorsProcessorTests { assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); assertFalse(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3")); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -371,8 +370,8 @@ public class DefaultCorsProcessorTests { assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); assertFalse(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("*")); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } @@ -388,8 +387,8 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)); - assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, + HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); } 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 3a5216c66e..64949a433e 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 @@ -28,8 +28,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.server.ServerWebExchange; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -70,8 +69,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -86,8 +85,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -98,8 +97,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); } @@ -124,8 +123,8 @@ public class DefaultCorsProcessorTests { assertEquals("*", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -143,8 +142,8 @@ public class DefaultCorsProcessorTests { assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -160,8 +159,8 @@ public class DefaultCorsProcessorTests { assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -173,8 +172,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -192,8 +191,8 @@ public class DefaultCorsProcessorTests { assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1")); assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2")); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -205,8 +204,8 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -219,8 +218,8 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); } @@ -233,8 +232,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertNull(response.getStatusCode()); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertEquals("GET,HEAD", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); } @@ -245,8 +244,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); } @@ -258,8 +257,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); } @@ -273,8 +272,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); } @@ -298,8 +297,8 @@ public class DefaultCorsProcessorTests { assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); assertEquals("GET,PUT", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -322,8 +321,8 @@ public class DefaultCorsProcessorTests { assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -344,8 +343,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -368,8 +367,8 @@ public class DefaultCorsProcessorTests { assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3")); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -390,8 +389,8 @@ public class DefaultCorsProcessorTests { assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("*")); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } @@ -409,8 +408,8 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)); - assertThat(response.getHeaders().get(VARY), contains(ORIGIN, - ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, + ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertNull(response.getStatusCode()); } diff --git a/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java index 1d72844a16..075548dd21 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java @@ -18,7 +18,6 @@ package org.springframework.web.filter.reactive; import java.time.Duration; -import org.hamcrest.Matchers; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -31,7 +30,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -81,7 +80,7 @@ public class HiddenHttpMethodFilterTests { public void filterWithInvalidMethodValue() { StepVerifier.create(postForm("_method=INVALID")) .consumeErrorWith(error -> { - assertThat(error, Matchers.instanceOf(IllegalArgumentException.class)); + assertThat(error).isInstanceOf(IllegalArgumentException.class); assertEquals("HttpMethod 'INVALID' not supported", error.getMessage()); }) .verify(); diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java index accfab8a07..f67df3be5a 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java @@ -29,8 +29,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartFile; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -86,12 +85,12 @@ public class StandardMultipartHttpServletRequestTests { MockHttpOutputMessage output = new MockHttpOutputMessage(); new FormHttpMessageConverter().write(map, null, output); - assertThat(output.getBodyAsString(StandardCharsets.UTF_8), containsString( + assertThat(output.getBodyAsString(StandardCharsets.UTF_8)).contains( "Content-Disposition: form-data; name=\"file\"; filename=\"myFile.txt\"\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 6\r\n" + "\r\n" + - "myBody\r\n")); + "myBody\r\n"); } 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 d918646324..107d547132 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 @@ -33,11 +33,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; @@ -715,73 +712,73 @@ public class UriComponentsBuilderTests { @Test public void queryParamWithValueWithEquals() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("https://example.com/foo?bar=baz").build(); - assertThat(uriComponents.toUriString(), equalTo("https://example.com/foo?bar=baz")); - assertThat(uriComponents.getQueryParams().get("bar").get(0), equalTo("baz")); + assertThat(uriComponents.toUriString()).isEqualTo("https://example.com/foo?bar=baz"); + assertThat(uriComponents.getQueryParams().get("bar").get(0)).isEqualTo("baz"); } @Test public void queryParamWithoutValueWithEquals() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("https://example.com/foo?bar=").build(); - assertThat(uriComponents.toUriString(), equalTo("https://example.com/foo?bar=")); - assertThat(uriComponents.getQueryParams().get("bar").get(0), equalTo("")); + assertThat(uriComponents.toUriString()).isEqualTo("https://example.com/foo?bar="); + assertThat(uriComponents.getQueryParams().get("bar").get(0)).isEqualTo(""); } @Test public void queryParamWithoutValueWithoutEquals() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("https://example.com/foo?bar").build(); - assertThat(uriComponents.toUriString(), equalTo("https://example.com/foo?bar")); + assertThat(uriComponents.toUriString()).isEqualTo("https://example.com/foo?bar"); // TODO [SPR-13537] Change equalTo(null) to equalTo(""). - assertThat(uriComponents.getQueryParams().get("bar").get(0), equalTo(null)); + assertThat(uriComponents.getQueryParams().get("bar").get(0)).isNull(); } @Test public void relativeUrls() { String baseUrl = "https://example.com"; - assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toString(), - equalTo(baseUrl + "/foo/../bar")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toUriString(), - equalTo(baseUrl + "/foo/../bar")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toUri().getPath(), - equalTo("/foo/../bar")); - assertThat(UriComponentsBuilder.fromUriString("../../").build().toString(), - equalTo("../../")); - assertThat(UriComponentsBuilder.fromUriString("../../").build().toUriString(), - equalTo("../../")); - assertThat(UriComponentsBuilder.fromUriString("../../").build().toUri().getPath(), - equalTo("../../")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toString(), - equalTo(baseUrl + "/foo/../bar")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toUriString(), - equalTo(baseUrl + "/foo/../bar")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toUri().getPath(), - equalTo("/foo/../bar")); + assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toString()) + .isEqualTo(baseUrl + "/foo/../bar"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toUriString()) + .isEqualTo(baseUrl + "/foo/../bar"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toUri().getPath()) + .isEqualTo("/foo/../bar"); + assertThat(UriComponentsBuilder.fromUriString("../../").build().toString()) + .isEqualTo("../../"); + assertThat(UriComponentsBuilder.fromUriString("../../").build().toUriString()) + .isEqualTo("../../"); + assertThat(UriComponentsBuilder.fromUriString("../../").build().toUri().getPath()) + .isEqualTo("../../"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toString()) + .isEqualTo(baseUrl + "/foo/../bar"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toUriString()) + .isEqualTo(baseUrl + "/foo/../bar"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toUri().getPath()) + .isEqualTo("/foo/../bar"); } @Test public void emptySegments() { String baseUrl = "https://example.com/abc/"; - assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("/x/y/z").build().toString(), - equalTo("https://example.com/abc/x/y/z")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl).pathSegment("x", "y", "z").build().toString(), - equalTo("https://example.com/abc/x/y/z")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("/x/").path("/y/z").build().toString(), - equalTo("https://example.com/abc/x/y/z")); - assertThat(UriComponentsBuilder.fromUriString(baseUrl).pathSegment("x").path("y").build().toString(), - equalTo("https://example.com/abc/x/y")); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("/x/y/z").build().toString()) + .isEqualTo("https://example.com/abc/x/y/z"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).pathSegment("x", "y", "z").build().toString()) + .isEqualTo("https://example.com/abc/x/y/z"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("/x/").path("/y/z").build().toString()) + .isEqualTo("https://example.com/abc/x/y/z"); + assertThat(UriComponentsBuilder.fromUriString(baseUrl).pathSegment("x").path("y").build().toString()) + .isEqualTo("https://example.com/abc/x/y"); } @Test public void parsesEmptyFragment() { UriComponents components = UriComponentsBuilder.fromUriString("/example#").build(); - assertThat(components.getFragment(), is(nullValue())); - assertThat(components.toString(), equalTo("/example")); + assertThat(components.getFragment()).isNull(); + assertThat(components.toString()).isEqualTo("/example"); } @Test // SPR-13257 public void parsesEmptyUri() { UriComponents components = UriComponentsBuilder.fromUriString("").build(); - assertThat(components.toString(), equalTo("")); + assertThat(components.toString()).isEqualTo(""); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java index 71d120ccba..93429843dd 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java @@ -27,12 +27,9 @@ import java.util.Collections; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.springframework.web.util.UriComponentsBuilder.fromUriString; @@ -193,7 +190,7 @@ public class UriComponentsTests { oos.writeObject(uriComponents); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); UriComponents readObject = (UriComponents) ois.readObject(); - assertThat(uriComponents.toString(), equalTo(readObject.toString())); + assertThat(uriComponents.toString()).isEqualTo(readObject.toString()); } @Test @@ -212,10 +209,10 @@ public class UriComponentsTests { UriComponents uric1 = UriComponentsBuilder.fromUriString(url).path("/{foo}").query("bar={baz}").build(); UriComponents uric2 = UriComponentsBuilder.fromUriString(url).path("/{foo}").query("bar={baz}").build(); UriComponents uric3 = UriComponentsBuilder.fromUriString(url).path("/{foo}").query("bin={baz}").build(); - assertThat(uric1, instanceOf(HierarchicalUriComponents.class)); - assertThat(uric1, equalTo(uric1)); - assertThat(uric1, equalTo(uric2)); - assertThat(uric1, not(equalTo(uric3))); + assertThat(uric1).isInstanceOf(HierarchicalUriComponents.class); + assertThat(uric1).isEqualTo(uric1); + assertThat(uric1).isEqualTo(uric2); + assertThat(uric1).isNotEqualTo(uric3); } @Test @@ -224,10 +221,10 @@ public class UriComponentsTests { UriComponents uric1 = UriComponentsBuilder.fromUriString(baseUrl + "/foo/bar").build(); UriComponents uric2 = UriComponentsBuilder.fromUriString(baseUrl + "/foo/bar").build(); UriComponents uric3 = UriComponentsBuilder.fromUriString(baseUrl + "/foo/bin").build(); - assertThat(uric1, instanceOf(OpaqueUriComponents.class)); - assertThat(uric1, equalTo(uric1)); - assertThat(uric1, equalTo(uric2)); - assertThat(uric1, not(equalTo(uric3))); + assertThat(uric1).isInstanceOf(OpaqueUriComponents.class); + assertThat(uric1).isEqualTo(uric1); + assertThat(uric1).isEqualTo(uric2); + assertThat(uric1).isNotEqualTo(uric3); } } 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 dc56016f21..42843dbfc9 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 @@ -23,7 +23,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.http.server.PathContainer; @@ -33,7 +32,6 @@ import org.springframework.web.util.pattern.PathPattern.PathRemainingMatchInfo; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -981,7 +979,7 @@ public class PathPatternTests { // Comparator patternComparator = new AntPathMatcher().getPatternComparator(""); // System.out.println(patternComparator.compare("/{foo}","/{foo}.*")); - assertThat(p1.compareTo(p2), Matchers.greaterThan(0)); + assertThat(p1.compareTo(p2)).isGreaterThan(0); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java index 6c56009815..f28e9b397a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java @@ -50,10 +50,7 @@ import org.springframework.web.server.WebExceptionHandler; import org.springframework.web.server.WebHandler; import org.springframework.web.server.handler.ExceptionHandlingWebHandler; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; @@ -89,8 +86,8 @@ public class DispatcherHandlerErrorTests { StepVerifier.create(mono) .consumeErrorWith(ex -> { - assertThat(ex, instanceOf(ResponseStatusException.class)); - assertThat(ex.getMessage(), is("404 NOT_FOUND \"No matching handler\"")); + assertThat(ex).isInstanceOf(ResponseStatusException.class); + assertThat(ex.getMessage()).isEqualTo("404 NOT_FOUND \"No matching handler\""); }) .verify(); @@ -126,10 +123,10 @@ public class DispatcherHandlerErrorTests { Mono publisher = this.dispatcherHandler.handle(exchange); StepVerifier.create(publisher) - .consumeErrorWith(error -> { - assertThat(error, instanceOf(IllegalStateException.class)); - assertThat(error.getMessage(), startsWith("No HandlerResultHandler")); - }) + .consumeErrorWith(error -> + assertThat(error) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("No HandlerResultHandler")) .verify(); } @@ -141,7 +138,7 @@ public class DispatcherHandlerErrorTests { Mono publisher = this.dispatcherHandler.handle(exchange); StepVerifier.create(publisher) - .consumeErrorWith(error -> assertThat(error, instanceOf(NotAcceptableStatusException.class))) + .consumeErrorWith(error -> assertThat(error).isInstanceOf(NotAcceptableStatusException.class)) .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java index 35dd7e1b15..491e954ea1 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java @@ -21,7 +21,6 @@ import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -49,7 +48,7 @@ import org.springframework.web.reactive.resource.ResourceWebHandler; import org.springframework.web.reactive.resource.VersionResourceResolver; import org.springframework.web.reactive.resource.WebJarsResourceResolver; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -99,11 +98,11 @@ public class ResourceHandlerRegistryTests { @Test public void cacheControl() { - assertThat(getHandler("/resources/**").getCacheControl(), Matchers.nullValue()); + assertThat(getHandler("/resources/**").getCacheControl()).isNull(); this.registration.setCacheControl(CacheControl.noCache().cachePrivate()); - assertThat(getHandler("/resources/**").getCacheControl().getHeaderValue(), - Matchers.equalTo(CacheControl.noCache().cachePrivate().getHeaderValue())); + assertThat(getHandler("/resources/**").getCacheControl().getHeaderValue()) + .isEqualTo(CacheControl.noCache().cachePrivate().getHeaderValue()); } @Test @@ -131,18 +130,18 @@ public class ResourceHandlerRegistryTests { ResourceWebHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isInstanceOf(CachingResourceResolver.class); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); - assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); - assertThat(resolvers.get(1), Matchers.equalTo(mockResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(cachingResolver.getCache()).isInstanceOf(ConcurrentMapCache.class); + assertThat(resolvers.get(1)).isEqualTo(mockResolver); + assertThat(resolvers.get(2)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(3)).isInstanceOf(PathResourceResolver.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(2)); - assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); - assertThat(transformers.get(1), Matchers.equalTo(mockTransformer)); + assertThat(transformers).hasSize(2); + assertThat(transformers.get(0)).isInstanceOf(CachingResourceTransformer.class); + assertThat(transformers.get(1)).isEqualTo(mockTransformer); Mockito.verify(mockTransformer).setResourceUrlProvider(resourceUrlProvider); } @@ -152,12 +151,12 @@ public class ResourceHandlerRegistryTests { ResourceWebHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(2)); - assertThat(resolvers.get(0), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(1), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers).hasSize(2); + assertThat(resolvers.get(0)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(1)).isInstanceOf(PathResourceResolver.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(0)); + assertThat(transformers).hasSize(0); } @Test @@ -171,17 +170,17 @@ public class ResourceHandlerRegistryTests { ResourceWebHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); - assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isInstanceOf(CachingResourceResolver.class); + assertThat(resolvers.get(1)).isSameAs(versionResolver); + assertThat(resolvers.get(2)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(3)).isInstanceOf(PathResourceResolver.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(3)); - assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); - assertThat(transformers.get(1), Matchers.instanceOf(CssLinkResourceTransformer.class)); - assertThat(transformers.get(2), Matchers.instanceOf(AppCacheManifestTransformer.class)); + assertThat(transformers).hasSize(3); + assertThat(transformers.get(0)).isInstanceOf(CachingResourceTransformer.class); + assertThat(transformers.get(1)).isInstanceOf(CssLinkResourceTransformer.class); + assertThat(transformers.get(2)).isInstanceOf(AppCacheManifestTransformer.class); } @Test @@ -206,17 +205,17 @@ public class ResourceHandlerRegistryTests { ResourceWebHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.sameInstance(cachingResolver)); - assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); - assertThat(resolvers.get(2), Matchers.sameInstance(webjarsResolver)); - assertThat(resolvers.get(3), Matchers.sameInstance(pathResourceResolver)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isSameAs(cachingResolver); + assertThat(resolvers.get(1)).isSameAs(versionResolver); + assertThat(resolvers.get(2)).isSameAs(webjarsResolver); + assertThat(resolvers.get(3)).isSameAs(pathResourceResolver); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(3)); - assertThat(transformers.get(0), Matchers.sameInstance(cachingTransformer)); - assertThat(transformers.get(1), Matchers.sameInstance(appCacheTransformer)); - assertThat(transformers.get(2), Matchers.sameInstance(cssLinkTransformer)); + assertThat(transformers).hasSize(3); + assertThat(transformers.get(0)).isSameAs(cachingTransformer); + assertThat(transformers.get(1)).isSameAs(appCacheTransformer); + assertThat(transformers.get(2)).isSameAs(cssLinkTransformer); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java index 7321228de5..079231ed61 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java @@ -67,8 +67,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT; @@ -341,16 +340,16 @@ public class BodyInsertersTests { dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); String content = new String(resultBytes, StandardCharsets.UTF_8); - assertThat(content, containsString("Content-Disposition: form-data; name=\"name\"\r\n" + + assertThat(content).contains("Content-Disposition: form-data; name=\"name\"\r\n" + "Content-Type: text/plain;charset=UTF-8\r\n" + "Content-Length: 6\r\n" + "\r\n" + - "value1")); - assertThat(content, containsString("Content-Disposition: form-data; name=\"name\"\r\n" + + "value1"); + assertThat(content).contains("Content-Disposition: form-data; name=\"name\"\r\n" + "Content-Type: text/plain;charset=UTF-8\r\n" + "Content-Length: 6\r\n" + "\r\n" + - "value2")); + "value2"); }) .expectComplete() .verify(); 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 e59d70e1cc..28eea503a0 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 @@ -29,7 +29,6 @@ import java.util.zip.CRC32; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -56,7 +55,7 @@ import org.springframework.http.client.reactive.JettyClientHttpConnector; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.http.codec.Pojo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -338,8 +337,8 @@ public class WebClientIntegrationTests { .bodyToFlux(Pojo.class); StepVerifier.create(result) - .consumeNextWith(p -> assertThat(p.getBar(), Matchers.is("bar1"))) - .consumeNextWith(p -> assertThat(p.getBar(), Matchers.is("bar2"))) + .consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("bar1")) + .consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("bar2")) .expectComplete() .verify(Duration.ofSeconds(3)); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java index 96e6277587..51b88f8016 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java @@ -29,8 +29,7 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -104,21 +103,20 @@ public class AppCacheManifestTransformerTests { byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream()); String content = new String(bytes, "UTF-8"); - assertThat("should rewrite resource links", content, - containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css")); - assertThat("should rewrite resource links", content, - containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css")); - assertThat("should rewrite resource links", content, - containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js")); + assertThat(content).as("rewrite resource links") + .contains("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css") + .contains("/static/bar-11e16cf79faee7ac698c805cf28248d2.css") + .contains("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js"); - assertThat("should not rewrite external resources", content, containsString("//example.org/style.css")); - assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png")); + assertThat(content).as("not rewrite external resources") + .contains("//example.org/style.css") + .contains("http://example.org/image.png"); // Not the same hash as Spring MVC // Hash is computed from links, and not from the linked content - assertThat("should generate fingerprint", content, - containsString("# Hash: 8eefc904df3bd46537fa7bdbbc5ab9fb")); + assertThat(content).as("generate fingerprint") + .contains("# Hash: 8eefc904df3bd46537fa7bdbbc5ab9fb"); } private Resource getResource(String filePath) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java index 33f0d4d531..4a61937313 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java @@ -23,9 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matchers; +import org.assertj.core.api.Condition; import org.junit.Before; import org.junit.Test; @@ -39,7 +37,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.util.pattern.PathPattern; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; @@ -138,11 +136,17 @@ public class ResourceUrlProviderTests { context.register(HandlerMappingConfiguration.class); context.refresh(); - assertThat(context.getBean(ResourceUrlProvider.class).getHandlerMap(), - Matchers.hasKey(pattern("/resources/**"))); + assertThat(context.getBean(ResourceUrlProvider.class).getHandlerMap()) + .hasKeySatisfying(pathPatternStringOf("/resources/**")); } + private Condition pathPatternStringOf(String expected) { + return new Condition( + actual -> actual != null && actual.getPatternString().equals(expected), + "Pattern %s", expected); + } + @Configuration @SuppressWarnings({"unused", "WeakerAccess"}) static class HandlerMappingConfiguration { @@ -163,30 +167,4 @@ public class ResourceUrlProviderTests { } } - private static PathPatternMatcher pattern(String pattern) { - return new PathPatternMatcher(pattern); - } - - private static class PathPatternMatcher extends BaseMatcher { - - private final String pattern; - - public PathPatternMatcher(String pattern) { - this.pattern = pattern; - } - - @Override - public boolean matches(Object item) { - if (item != null && item instanceof PathPattern) { - return ((PathPattern) item).getPatternString().equals(pattern); - } - return false; - } - - @Override - public void describeTo(Description description) { - - } - } - } 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 73aee89254..e85321a6dd 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 @@ -55,10 +55,9 @@ import org.springframework.web.server.MethodNotAllowedException; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; @@ -287,7 +286,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(handler.handle(exchange)) .expectErrorSatisfies(err -> { - assertThat(err, instanceOf(ResponseStatusException.class)); + assertThat(err).isInstanceOf(ResponseStatusException.class); assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); }).verify(TIMEOUT); } @@ -333,7 +332,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, requestPath); StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { - assertThat(err, instanceOf(ResponseStatusException.class)); + assertThat(err).isInstanceOf(ResponseStatusException.class); assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); }) .verify(TIMEOUT); @@ -428,7 +427,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "js/"); StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { - assertThat(err, instanceOf(ResponseStatusException.class)); + assertThat(err).isInstanceOf(ResponseStatusException.class); assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); }).verify(TIMEOUT); } @@ -439,7 +438,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "underscorejs/"); StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { - assertThat(err, instanceOf(ResponseStatusException.class)); + assertThat(err).isInstanceOf(ResponseStatusException.class); assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); }).verify(TIMEOUT); } @@ -450,7 +449,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, ""); StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { - assertThat(err, instanceOf(ResponseStatusException.class)); + assertThat(err).isInstanceOf(ResponseStatusException.class); assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); }).verify(TIMEOUT); } @@ -485,7 +484,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(mono) .expectErrorSatisfies(err -> { - assertThat(err, instanceOf(ResponseStatusException.class)); + assertThat(err).isInstanceOf(ResponseStatusException.class); assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); }).verify(TIMEOUT); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java index 72ec49e651..1251f44181 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java @@ -23,7 +23,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; @@ -34,9 +33,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.given; @@ -179,7 +176,7 @@ public class VersionResourceResolverTests { assertEquals(expected.getFilename(), actual.getFilename()); verify(this.versionStrategy, times(1)).getResourceVersion(expected); - assertThat(actual, instanceOf(HttpResource.class)); + assertThat(actual).isInstanceOf(HttpResource.class); assertEquals("\"" + version + "\"", ((HttpResource)actual).getResponseHeaders().getETag()); } @@ -203,19 +200,19 @@ public class VersionResourceResolverTests { this.resolver.addFixedVersionStrategy("fixedversion", "/js/**", "/css/**", "/fixedversion/css/**"); - assertThat(this.resolver.getStrategyMap().size(), is(4)); + assertThat(this.resolver.getStrategyMap()).hasSize(4); - assertThat(this.resolver.getStrategyForPath("js/something.js"), - Matchers.instanceOf(FixedVersionStrategy.class)); + assertThat(this.resolver.getStrategyForPath("js/something.js")) + .isInstanceOf(FixedVersionStrategy.class); - assertThat(this.resolver.getStrategyForPath("fixedversion/js/something.js"), - Matchers.instanceOf(FixedVersionStrategy.class)); + assertThat(this.resolver.getStrategyForPath("fixedversion/js/something.js")) + .isInstanceOf(FixedVersionStrategy.class); - assertThat(this.resolver.getStrategyForPath("css/something.css"), - Matchers.instanceOf(FixedVersionStrategy.class)); + assertThat(this.resolver.getStrategyForPath("css/something.css")) + .isInstanceOf(FixedVersionStrategy.class); - assertThat(this.resolver.getStrategyForPath("fixedversion/css/something.css"), - Matchers.instanceOf(FixedVersionStrategy.class)); + assertThat(this.resolver.getStrategyForPath("fixedversion/css/something.css")) + .isInstanceOf(FixedVersionStrategy.class); } @Test // SPR-15372 @@ -223,7 +220,7 @@ public class VersionResourceResolverTests { given(this.chain.resolveUrlPath("/foo.css", this.locations)).willReturn(Mono.just("/foo.css")); String resolved = this.resolver.resolveUrlPathInternal("/foo.css", this.locations, this.chain) .block(Duration.ofMillis(1000)); - assertThat(resolved, is("/foo.css")); + assertThat(resolved).isEqualTo("/foo.css"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java index f7ddeb14c7..ee500e6530 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java @@ -35,8 +35,8 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.util.pattern.PathPattern; import org.springframework.web.util.pattern.PathPatternParser; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -111,8 +111,8 @@ public class HandlerMethodMappingTests { this.mapping.registerMapping(key1, this.handler, this.method1); this.mapping.registerMapping(key2, this.handler, this.method2); - assertThat(this.mapping.getMappingRegistry().getMappings().keySet(), - Matchers.contains(key1, key2)); + assertThat(this.mapping.getMappingRegistry().getMappings()) + .containsKeys(key1, key2); } @Test @@ -124,7 +124,8 @@ public class HandlerMethodMappingTests { this.mapping.registerMapping(key1, handler1, this.method1); this.mapping.registerMapping(key2, handler2, this.method1); - assertThat(this.mapping.getMappingRegistry().getMappings().keySet(), Matchers.contains(key1, key2)); + assertThat(this.mapping.getMappingRegistry().getMappings()) + .containsKeys(key1, key2); } @Test @@ -139,7 +140,7 @@ public class HandlerMethodMappingTests { result = this.mapping.getHandler(MockServerWebExchange.from(MockServerHttpRequest.get(key))); assertNull(result.block()); - assertThat(this.mapping.getMappingRegistry().getMappings().keySet(), Matchers.not(Matchers.contains(key))); + assertThat(this.mapping.getMappingRegistry().getMappings().keySet()).isNotEqualTo(Matchers.contains(key)); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java index 1c147864f4..7101f20b01 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java @@ -42,10 +42,9 @@ import org.springframework.web.reactive.HandlerResult; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.UnsupportedMediaTypeStatusException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; @@ -158,7 +157,7 @@ public class InvocableHandlerMethodTests { Mono mono = invoke(new TestController(), method); assertHandlerResultValue(mono, "created"); - assertThat(this.exchange.getResponse().getStatusCode(), is(HttpStatus.CREATED)); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.CREATED); } @Test 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 c257b2b9e9..3f25dbcc17 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 @@ -58,8 +58,7 @@ import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.UnsupportedMediaTypeStatusException; import org.springframework.web.util.pattern.PathPattern; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -187,8 +186,8 @@ public class RequestMappingInfoHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(get("/params")); Mono mono = this.handlerMapping.getHandler(exchange); assertError(mono, ServerWebInputException.class, ex -> { - assertThat(ex.getReason(), containsString("[foo=bar]")); - assertThat(ex.getReason(), containsString("[bar=baz]")); + assertThat(ex.getReason()).contains("[foo=bar]"); + assertThat(ex.getReason()).contains("[bar=baz]"); }); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java index f36d187abe..7a0cab866f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java @@ -38,8 +38,6 @@ import org.springframework.web.reactive.config.WebFluxConfigurationSupport; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -116,8 +114,8 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte ResponseEntity entity = performOptions("/cors", this.headers, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); - assertThat(entity.getHeaders().getAccessControlAllowMethods(), - contains(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST)); + assertThat(entity.getHeaders().getAccessControlAllowMethods()) + .containsExactly(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST); } @Test @@ -143,7 +141,8 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte ResponseEntity entity = performOptions("/cors-restricted", this.headers, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("https://foo", entity.getHeaders().getAccessControlAllowOrigin()); - assertThat(entity.getHeaders().getAccessControlAllowMethods(), contains(HttpMethod.GET, HttpMethod.POST)); + assertThat(entity.getHeaders().getAccessControlAllowMethods()) + .containsExactly(HttpMethod.GET, HttpMethod.POST); } @Test @@ -152,10 +151,12 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte ResponseEntity entity = performOptions("/ambiguous", this.headers, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin()); - assertThat(entity.getHeaders().getAccessControlAllowMethods(), contains(HttpMethod.GET)); + assertThat(entity.getHeaders().getAccessControlAllowMethods()) + .containsExactly(HttpMethod.GET); assertEquals(true, entity.getHeaders().getAccessControlAllowCredentials()); - assertThat(entity.getHeaders().get(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, - HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); + assertThat(entity.getHeaders().get(HttpHeaders.VARY)) + .containsExactly(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, + HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java index ac4cd96221..106c7dcfd9 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 @@ -25,7 +25,6 @@ import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hamcrest.Matchers; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -38,7 +37,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -99,7 +98,7 @@ public class WebSocketIntegrationTests extends AbstractWebSocketIntegrationTests .block(TIMEOUT); HandshakeInfo info = infoRef.get(); - assertThat(info.getHeaders().getFirst("Upgrade"), Matchers.equalToIgnoringCase("websocket")); + assertThat(info.getHeaders().getFirst("Upgrade")).isEqualToIgnoringCase("websocket"); assertEquals(protocol, info.getHeaders().getFirst("Sec-WebSocket-Protocol")); assertEquals("Wrong protocol accepted", protocol, info.getSubProtocol()); assertEquals("Wrong protocol detected on the server side", protocol, output.block(TIMEOUT)); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java index 8a52bfe3a9..c463211d1b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java @@ -20,7 +20,6 @@ import java.util.Arrays; import java.util.Map; import java.util.function.Supplier; -import org.hamcrest.Matchers; import org.junit.Test; import reactor.core.publisher.Mono; @@ -33,8 +32,7 @@ import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; import org.springframework.web.server.ServerWebExchange; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; @@ -67,10 +65,11 @@ public class HandshakeWebSocketServiceTests { assertNotNull(info); Map attributes = info.getAttributes(); - assertEquals(3, attributes.size()); - assertThat(attributes, Matchers.hasEntry("a1", "v1")); - assertThat(attributes, Matchers.hasEntry("a3", "v3")); - assertThat(attributes, Matchers.hasEntry("a5", "v5")); + assertThat(attributes) + .hasSize(3) + .containsEntry("a1", "v1") + .containsEntry("a3", "v3") + .containsEntry("a5", "v5"); } private MockServerHttpRequest initHandshakeRequest() { diff --git a/spring-webmvc/spring-webmvc.gradle b/spring-webmvc/spring-webmvc.gradle index 9baf62c6b4..071e453efd 100644 --- a/spring-webmvc/spring-webmvc.gradle +++ b/spring-webmvc/spring-webmvc.gradle @@ -65,6 +65,7 @@ dependencies { exclude group: "xom", module: "xom" exclude group: "xerces", module: "xercesImpl" } + testCompile("org.xmlunit:xmlunit-assertj:2.6.2") testCompile("org.xmlunit:xmlunit-matchers:2.6.2") testCompile("org.hibernate:hibernate-validator:6.0.16.Final") testCompile("io.projectreactor:reactor-core") 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 a5bb4a0482..56e66836c8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java @@ -47,10 +47,6 @@ import org.springframework.web.servlet.SimpleWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -131,8 +127,8 @@ public class ContextLoaderTests { listener.contextInitialized(new ServletContextEvent(sc)); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); TestBean testBean = wac.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("testName")); - assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue()); + assertThat(testBean.getName()).isEqualTo("testName"); + assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull(); } @Test @@ -146,8 +142,8 @@ public class ContextLoaderTests { listener.contextInitialized(new ServletContextEvent(sc)); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); TestBean testBean = wac.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("testName")); - assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue()); + assertThat(testBean.getName()).isEqualTo("testName"); + assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull(); } @Test @@ -161,8 +157,8 @@ public class ContextLoaderTests { listener.contextInitialized(new ServletContextEvent(sc)); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); TestBean testBean = wac.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("testName")); - assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue()); + assertThat(testBean.getName()).isEqualTo("testName"); + assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull(); } @Test @@ -175,8 +171,8 @@ public class ContextLoaderTests { listener.contextInitialized(new ServletContextEvent(sc)); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); TestBean testBean = wac.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("testName")); - assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue()); + assertThat(testBean.getName()).isEqualTo("testName"); + assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull(); } @Test @@ -190,8 +186,8 @@ public class ContextLoaderTests { listener.contextInitialized(new ServletContextEvent(sc)); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); TestBean testBean = wac.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("testName")); - assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue()); + assertThat(testBean.getName()).isEqualTo("testName"); + assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull(); } @Test @@ -205,8 +201,8 @@ public class ContextLoaderTests { listener.contextInitialized(new ServletContextEvent(sc)); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); TestBean testBean = wac.getBean(TestBean.class); - assertThat(testBean.getName(), equalTo("testName")); - assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue()); + assertThat(testBean.getName()).isEqualTo("testName"); + assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull(); } @Test @@ -381,7 +377,7 @@ public class ContextLoaderTests { // test that ApplicationContextInitializers can access ServletContext properties // via the environment (SPR-8991) String value = applicationContext.getEnvironment().getRequiredProperty("someProperty"); - assertThat(value, is("someValue")); + assertThat(value).isEqualTo("someValue"); } } 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 abc7ff3825..69077621af 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java @@ -38,8 +38,6 @@ import org.springframework.web.context.support.XmlWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -91,10 +89,10 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes @Test @SuppressWarnings("deprecation") public void environmentMerge() { - assertThat(this.root.getEnvironment().acceptsProfiles("rootProfile1"), is(true)); - assertThat(this.root.getEnvironment().acceptsProfiles("wacProfile1"), is(false)); - assertThat(this.applicationContext.getEnvironment().acceptsProfiles("rootProfile1"), is(true)); - assertThat(this.applicationContext.getEnvironment().acceptsProfiles("wacProfile1"), is(true)); + assertThat(this.root.getEnvironment().acceptsProfiles("rootProfile1")).isTrue(); + assertThat(this.root.getEnvironment().acceptsProfiles("wacProfile1")).isFalse(); + assertThat(this.applicationContext.getEnvironment().acceptsProfiles("rootProfile1")).isTrue(); + assertThat(this.applicationContext.getEnvironment().acceptsProfiles("wacProfile1")).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 81869f46b9..e689c4a5b2 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 @@ -58,13 +58,9 @@ import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -779,10 +775,10 @@ public class DispatcherServletTests { public void environmentOperations() { DispatcherServlet servlet = new DispatcherServlet(); ConfigurableEnvironment defaultEnv = servlet.getEnvironment(); - assertThat(defaultEnv, notNullValue()); + assertThat(defaultEnv).isNotNull(); ConfigurableEnvironment env1 = new StandardServletEnvironment(); servlet.setEnvironment(env1); // should succeed - assertThat(servlet.getEnvironment(), sameInstance(env1)); + assertThat(servlet.getEnvironment()).isSameAs(env1); assertThatIllegalArgumentException().as("non-configurable Environment").isThrownBy(() -> servlet.setEnvironment(new DummyEnvironment())); class CustomServletEnvironment extends StandardServletEnvironment { } @@ -793,7 +789,7 @@ public class DispatcherServletTests { return new CustomServletEnvironment(); } }; - assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.class)); + assertThat(custom.getEnvironment()).isInstanceOf(CustomServletEnvironment.class); } @Test @@ -804,7 +800,7 @@ public class DispatcherServletTests { servlet.setDispatchOptionsRequest(false); servlet.service(request, response); verify(response, never()).getHeader(anyString()); // SPR-10341 - assertThat(response.getHeader("Allow"), equalTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH")); + assertThat(response.getHeader("Allow")).isEqualTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); } @Test 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 4b140dec84..0dd97cb11e 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 @@ -18,7 +18,6 @@ package org.springframework.web.servlet.config; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; @@ -50,7 +49,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import org.springframework.web.servlet.mvc.method.annotation.ServletWebArgumentResolverAdapter; import org.springframework.web.util.UrlPathHelper; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -90,11 +89,10 @@ public class AnnotationDrivenBeanDefinitionParserTests { assertTrue(hm.useSuffixPatternMatch()); assertFalse(hm.useTrailingSlashMatch()); assertTrue(hm.useRegisteredSuffixPatternMatch()); - assertThat(hm.getUrlPathHelper(), Matchers.instanceOf(TestPathHelper.class)); - assertThat(hm.getPathMatcher(), Matchers.instanceOf(TestPathMatcher.class)); + assertThat(hm.getUrlPathHelper()).isInstanceOf(TestPathHelper.class); + assertThat(hm.getPathMatcher()).isInstanceOf(TestPathMatcher.class); List fileExtensions = hm.getContentNegotiationManager().getAllFileExtensions(); - assertThat(fileExtensions, Matchers.contains("xml")); - assertThat(fileExtensions, Matchers.hasSize(1)); + assertThat(fileExtensions).containsExactly("xml"); } @Test 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 bde5271843..0218e0d271 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 @@ -39,7 +39,6 @@ import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.apache.tiles.definition.UnresolvingLocaleDefinitionsFactory; -import org.hamcrest.Matchers; import org.joda.time.LocalDate; import org.junit.Before; import org.junit.Test; @@ -141,10 +140,8 @@ import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesViewResolver; import org.springframework.web.util.UrlPathHelper; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -379,8 +376,8 @@ public class MvcNamespaceTests { List> interceptors = beans.values().stream() .map(mappedInterceptor -> mappedInterceptor.getInterceptor().getClass()) .collect(Collectors.toList()); - assertThat(interceptors, containsInAnyOrder(ConversionServiceExposingInterceptor.class, - ResourceUrlProviderExposingInterceptor.class)); + assertThat(interceptors).contains(ConversionServiceExposingInterceptor.class, + ResourceUrlProviderExposingInterceptor.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/resources/foo.css"); @@ -427,21 +424,21 @@ public class MvcNamespaceTests { assertNotNull(handler.getUrlPathHelper()); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); - assertThat(resolvers.get(1), Matchers.instanceOf(VersionResourceResolver.class)); - assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isInstanceOf(CachingResourceResolver.class); + assertThat(resolvers.get(1)).isInstanceOf(VersionResourceResolver.class); + assertThat(resolvers.get(2)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(3)).isInstanceOf(PathResourceResolver.class); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); - assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); + assertThat(cachingResolver.getCache()).isInstanceOf(ConcurrentMapCache.class); assertEquals("test-resource-cache", cachingResolver.getCache().getName()); VersionResourceResolver versionResolver = (VersionResourceResolver) resolvers.get(1); - assertThat(versionResolver.getStrategyMap().get("/**/*.js"), - Matchers.instanceOf(FixedVersionStrategy.class)); - assertThat(versionResolver.getStrategyMap().get("/**"), - Matchers.instanceOf(ContentVersionStrategy.class)); + assertThat(versionResolver.getStrategyMap().get("/**/*.js")) + .isInstanceOf(FixedVersionStrategy.class); + assertThat(versionResolver.getStrategyMap().get("/**")) + .isInstanceOf(ContentVersionStrategy.class); PathResourceResolver pathResolver = (PathResourceResolver) resolvers.get(3); Map locationCharsets = pathResolver.getLocationCharsets(); @@ -449,13 +446,13 @@ public class MvcNamespaceTests { assertEquals(StandardCharsets.ISO_8859_1, locationCharsets.values().iterator().next()); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(3)); - assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); - assertThat(transformers.get(1), Matchers.instanceOf(CssLinkResourceTransformer.class)); - assertThat(transformers.get(2), Matchers.instanceOf(AppCacheManifestTransformer.class)); + assertThat(transformers).hasSize(3); + assertThat(transformers.get(0)).isInstanceOf(CachingResourceTransformer.class); + assertThat(transformers.get(1)).isInstanceOf(CssLinkResourceTransformer.class); + assertThat(transformers.get(2)).isInstanceOf(AppCacheManifestTransformer.class); CachingResourceTransformer cachingTransformer = (CachingResourceTransformer) transformers.get(0); - assertThat(cachingTransformer.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); + assertThat(cachingTransformer.getCache()).isInstanceOf(ConcurrentMapCache.class); assertEquals("test-resource-cache", cachingTransformer.getCache().getName()); } @@ -470,26 +467,26 @@ public class MvcNamespaceTests { ResourceHttpRequestHandler.class); assertNotNull(handler); - assertThat(handler.getCacheControl().getHeaderValue(), - Matchers.equalTo(CacheControl.maxAge(1, TimeUnit.HOURS) - .sMaxAge(30, TimeUnit.MINUTES).cachePublic().getHeaderValue())); + assertThat(handler.getCacheControl().getHeaderValue()) + .isEqualTo(CacheControl.maxAge(1, TimeUnit.HOURS) + .sMaxAge(30, TimeUnit.MINUTES).cachePublic().getHeaderValue()); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(3)); - assertThat(resolvers.get(0), Matchers.instanceOf(VersionResourceResolver.class)); - assertThat(resolvers.get(1), Matchers.instanceOf(EncodedResourceResolver.class)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers).hasSize(3); + assertThat(resolvers.get(0)).isInstanceOf(VersionResourceResolver.class); + assertThat(resolvers.get(1)).isInstanceOf(EncodedResourceResolver.class); + assertThat(resolvers.get(2)).isInstanceOf(PathResourceResolver.class); VersionResourceResolver versionResolver = (VersionResourceResolver) resolvers.get(0); - assertThat(versionResolver.getStrategyMap().get("/**/*.js"), - Matchers.instanceOf(FixedVersionStrategy.class)); - assertThat(versionResolver.getStrategyMap().get("/**"), - Matchers.instanceOf(ContentVersionStrategy.class)); + assertThat(versionResolver.getStrategyMap().get("/**/*.js")) + .isInstanceOf(FixedVersionStrategy.class); + assertThat(versionResolver.getStrategyMap().get("/**")) + .isInstanceOf(ContentVersionStrategy.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(2)); - assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); - assertThat(transformers.get(1), Matchers.instanceOf(AppCacheManifestTransformer.class)); + assertThat(transformers).hasSize(2); + assertThat(transformers.get(0)).isInstanceOf(CachingResourceTransformer.class); + assertThat(transformers.get(1)).isInstanceOf(AppCacheManifestTransformer.class); } @Test @@ -702,7 +699,7 @@ public class MvcNamespaceTests { ParameterizableViewController redirectViewController = (ParameterizableViewController) hm.getUrlMap().get("/old"); assertNotNull(redirectViewController); - assertThat(redirectViewController.getView(), Matchers.instanceOf(RedirectView.class)); + assertThat(redirectViewController.getView()).isInstanceOf(RedirectView.class); ParameterizableViewController statusViewController = (ParameterizableViewController) hm.getUrlMap().get("/bad"); assertNotNull(statusViewController); @@ -775,7 +772,7 @@ public class MvcNamespaceTests { assertEquals(TilesViewResolver.class, resolvers.get(2).getClass()); resolver = resolvers.get(3); - assertThat(resolver, instanceOf(FreeMarkerViewResolver.class)); + assertThat(resolver).isInstanceOf(FreeMarkerViewResolver.class); accessor = new DirectFieldAccessor(resolver); assertEquals("freemarker-", accessor.getPropertyValue("prefix")); assertEquals(".freemarker", accessor.getPropertyValue("suffix")); @@ -783,14 +780,14 @@ public class MvcNamespaceTests { assertEquals(1024, accessor.getPropertyValue("cacheLimit")); resolver = resolvers.get(4); - assertThat(resolver, instanceOf(GroovyMarkupViewResolver.class)); + assertThat(resolver).isInstanceOf(GroovyMarkupViewResolver.class); accessor = new DirectFieldAccessor(resolver); assertEquals("", accessor.getPropertyValue("prefix")); assertEquals(".tpl", accessor.getPropertyValue("suffix")); assertEquals(1024, accessor.getPropertyValue("cacheLimit")); resolver = resolvers.get(5); - assertThat(resolver, instanceOf(ScriptTemplateViewResolver.class)); + assertThat(resolver).isInstanceOf(ScriptTemplateViewResolver.class); accessor = new DirectFieldAccessor(resolver); assertEquals("", accessor.getPropertyValue("prefix")); assertEquals("", accessor.getPropertyValue("suffix")); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java index c73ad64fa4..c162ff8a42 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java @@ -21,7 +21,6 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -49,7 +48,7 @@ import org.springframework.web.servlet.resource.VersionResourceResolver; import org.springframework.web.servlet.resource.WebJarsResourceResolver; import org.springframework.web.util.UrlPathHelper; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -111,12 +110,11 @@ public class ResourceHandlerRegistryTests { @Test public void cacheControl() { - assertThat(getHandler("/resources/**").getCacheControl(), - Matchers.nullValue()); + assertThat(getHandler("/resources/**").getCacheControl()).isNull(); this.registration.setCacheControl(CacheControl.noCache().cachePrivate()); - assertThat(getHandler("/resources/**").getCacheControl().getHeaderValue(), - Matchers.equalTo(CacheControl.noCache().cachePrivate().getHeaderValue())); + assertThat(getHandler("/resources/**").getCacheControl().getHeaderValue()) + .isEqualTo(CacheControl.noCache().cachePrivate().getHeaderValue()); } @Test @@ -141,18 +139,18 @@ public class ResourceHandlerRegistryTests { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isInstanceOf(CachingResourceResolver.class); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); - assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); - assertThat(resolvers.get(1), Matchers.equalTo(mockResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(cachingResolver.getCache()).isInstanceOf(ConcurrentMapCache.class); + assertThat(resolvers.get(1)).isEqualTo(mockResolver); + assertThat(resolvers.get(2)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(3)).isInstanceOf(PathResourceResolver.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(2)); - assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); - assertThat(transformers.get(1), Matchers.equalTo(mockTransformer)); + assertThat(transformers).hasSize(2); + assertThat(transformers.get(0)).isInstanceOf(CachingResourceTransformer.class); + assertThat(transformers.get(1)).isEqualTo(mockTransformer); } @Test @@ -161,12 +159,12 @@ public class ResourceHandlerRegistryTests { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(2)); - assertThat(resolvers.get(0), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(1), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers).hasSize(2); + assertThat(resolvers.get(0)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(1)).isInstanceOf(PathResourceResolver.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(0)); + assertThat(transformers).isEmpty(); } @Test @@ -180,17 +178,17 @@ public class ResourceHandlerRegistryTests { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); - assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); - assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isInstanceOf(CachingResourceResolver.class); + assertThat(resolvers.get(1)).isSameAs(versionResolver); + assertThat(resolvers.get(2)).isInstanceOf(WebJarsResourceResolver.class); + assertThat(resolvers.get(3)).isInstanceOf(PathResourceResolver.class); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(3)); - assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); - assertThat(transformers.get(1), Matchers.instanceOf(CssLinkResourceTransformer.class)); - assertThat(transformers.get(2), Matchers.instanceOf(AppCacheManifestTransformer.class)); + assertThat(transformers).hasSize(3); + assertThat(transformers.get(0)).isInstanceOf(CachingResourceTransformer.class); + assertThat(transformers.get(1)).isInstanceOf(CssLinkResourceTransformer.class); + assertThat(transformers.get(2)).isInstanceOf(AppCacheManifestTransformer.class); } @Test @@ -215,17 +213,17 @@ public class ResourceHandlerRegistryTests { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); - assertThat(resolvers.get(0), Matchers.sameInstance(cachingResolver)); - assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); - assertThat(resolvers.get(2), Matchers.sameInstance(webjarsResolver)); - assertThat(resolvers.get(3), Matchers.sameInstance(pathResourceResolver)); + assertThat(resolvers).hasSize(4); + assertThat(resolvers.get(0)).isSameAs(cachingResolver); + assertThat(resolvers.get(1)).isSameAs(versionResolver); + assertThat(resolvers.get(2)).isSameAs(webjarsResolver); + assertThat(resolvers.get(3)).isSameAs(pathResourceResolver); List transformers = handler.getResourceTransformers(); - assertThat(transformers, Matchers.hasSize(3)); - assertThat(transformers.get(0), Matchers.sameInstance(cachingTransformer)); - assertThat(transformers.get(1), Matchers.sameInstance(appCacheTransformer)); - assertThat(transformers.get(2), Matchers.sameInstance(cssLinkTransformer)); + assertThat(transformers).hasSize(3); + assertThat(transformers.get(0)).isSameAs(cachingTransformer); + assertThat(transformers.get(1)).isSameAs(appCacheTransformer); + assertThat(transformers.get(2)).isSameAs(cssLinkTransformer); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingTests.java index b11c0a9709..655c982e12 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingTests.java @@ -21,7 +21,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -34,7 +33,8 @@ import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.support.WebContentGenerator; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for @@ -66,8 +66,8 @@ public class HandlerMappingTests { this.handlerMapping.setInterceptors(mappedInterceptor1, i2, mappedInterceptor3, i4); this.handlerMapping.setApplicationContext(this.context); HandlerExecutionChain chain = this.handlerMapping.getHandlerExecutionChain(new SimpleHandler(), this.request); - assertThat(chain.getInterceptors(), Matchers.arrayContaining( - mappedInterceptor1.getInterceptor(), i2, mappedInterceptor3.getInterceptor(), i4)); + assertThat(chain.getInterceptors()).contains( + mappedInterceptor1.getInterceptor(), i2, mappedInterceptor3.getInterceptor(), i4); } class TestHandlerMapping extends AbstractHandlerMapping { 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 c9e74cb2be..4e2c8881fc 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 @@ -18,15 +18,15 @@ package org.springframework.web.servlet.mvc; import java.util.Properties; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; + + /** * @author Rick Evans @@ -47,7 +47,7 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); Iterable cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.hasItem("max-age=10")); + assertThat(cacheControlHeaders).contains("max-age=10"); } @Test @@ -64,14 +64,14 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); Iterable cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.emptyIterable()); + assertThat(cacheControlHeaders).isEmpty(); // request.setRequestURI("http://localhost:7070/example/bingo.html"); request.setRequestURI("example/bingo.html"); interceptor.preHandle(request, response, null); cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.hasItem("max-age=10")); + assertThat(cacheControlHeaders).contains("max-age=10"); } @Test @@ -82,7 +82,7 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); Iterable cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.contains("no-store")); + assertThat(cacheControlHeaders).contains("no-store"); } @Test @@ -93,9 +93,9 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); Iterable expiresHeaders = response.getHeaders("Expires"); - assertThat(expiresHeaders, Matchers.emptyIterable()); + assertThat(expiresHeaders).isEmpty(); Iterable cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.emptyIterable()); + assertThat(cacheControlHeaders).isEmpty(); } // SPR-13252, SPR-14053 @@ -108,8 +108,8 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); - assertThat(response.getHeader("Pragma"), is("")); - assertThat(response.getHeader("Expires"), is("")); + assertThat(response.getHeader("Pragma")).isEqualTo(""); + assertThat(response.getHeader("Expires")).isEqualTo(""); } // SPR-13252, SPR-14053 @@ -124,8 +124,8 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); - assertThat(response.getHeader("Pragma"), is("")); - assertThat(response.getHeader("Expires"), is("")); + assertThat(response.getHeader("Pragma")).isEqualTo(""); + assertThat(response.getHeader("Expires")).isEqualTo(""); } @SuppressWarnings("deprecation") @@ -144,11 +144,11 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); Iterable expiresHeaders = response.getHeaders("Expires"); - assertThat(expiresHeaders, Matchers.iterableWithSize(1)); + assertThat(expiresHeaders).hasSize(1); Iterable cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.contains("no-cache", "no-store")); + assertThat(cacheControlHeaders).containsExactly("no-cache", "no-store"); Iterable pragmaHeaders = response.getHeaders("Pragma"); - assertThat(pragmaHeaders, Matchers.contains("no-cache")); + assertThat(pragmaHeaders).containsExactly("no-cache"); // request.setRequestURI("https://example.org/page.cache.html"); request = new MockHttpServletRequest("GET", "foo/page.cache.html"); @@ -156,9 +156,9 @@ public class WebContentInterceptorTests { interceptor.preHandle(request, response, null); expiresHeaders = response.getHeaders("Expires"); - assertThat(expiresHeaders, Matchers.iterableWithSize(1)); + assertThat(expiresHeaders).hasSize(1); cacheControlHeaders = response.getHeaders("Cache-Control"); - assertThat(cacheControlHeaders, Matchers.contains("max-age=10, must-revalidate")); + assertThat(cacheControlHeaders).containsExactly("max-age=10, must-revalidate"); } @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 0ae36ba176..155b06b864 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 @@ -29,7 +29,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.Date; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -58,8 +57,8 @@ import org.springframework.web.method.support.ModelAndViewContainer; import static java.time.Instant.ofEpochMilli; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -576,7 +575,7 @@ public class HttpEntityMethodProcessorMockTests { then(resourceMessageConverter).should(times(1)).write( any(InputStreamResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); assertEquals(200, servletResponse.getStatus()); - assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES), Matchers.isEmptyOrNullString()); + assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES)).isNull(); } @Test //SPR-16921 diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java index b3a58e1b11..95d2efebf8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; -import org.hamcrest.Matchers; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.After; @@ -62,13 +61,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromController; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromMappingName; @@ -104,32 +98,32 @@ public class MvcUriComponentsBuilderTests { @Test public void fromControllerPlain() { UriComponents uriComponents = fromController(PersonControllerImpl.class).build(); - assertThat(uriComponents.toUriString(), Matchers.endsWith("/people")); + assertThat(uriComponents.toUriString()).endsWith("/people"); } @Test public void fromControllerUriTemplate() { UriComponents uriComponents = fromController(PersonsAddressesController.class).buildAndExpand(15); - assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses")); + assertThat(uriComponents.toUriString()).endsWith("/people/15/addresses"); } @Test public void fromControllerSubResource() { UriComponents uriComponents = fromController(PersonControllerImpl.class).pathSegment("something").build(); - assertThat(uriComponents.toUriString(), endsWith("/people/something")); + assertThat(uriComponents.toUriString()).endsWith("/people/something"); } @Test public void fromControllerTwoTypeLevelMappings() { UriComponents uriComponents = fromController(InvalidController.class).build(); - assertThat(uriComponents.toUriString(), is("http://localhost/persons")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/persons"); } @Test public void fromControllerNotMapped() { UriComponents uriComponents = fromController(UnmappedController.class).build(); - assertThat(uriComponents.toUriString(), is("http://localhost/")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/"); } @Test @@ -158,7 +152,7 @@ public class MvcUriComponentsBuilderTests { adaptRequestFromForwardedHeaders(); UriComponents uriComponents = fromController(PersonControllerImpl.class).build(); - assertThat(uriComponents.toUriString(), startsWith("https://somethingDifferent")); + assertThat(uriComponents.toUriString()).startsWith("https://somethingDifferent"); } @Test @@ -168,7 +162,7 @@ public class MvcUriComponentsBuilderTests { adaptRequestFromForwardedHeaders(); UriComponents uriComponents = fromController(PersonControllerImpl.class).build(); - assertThat(uriComponents.toUriString(), startsWith("https://foobar:8088")); + assertThat(uriComponents.toUriString()).startsWith("https://foobar:8088"); } @Test @@ -178,7 +172,7 @@ public class MvcUriComponentsBuilderTests { adaptRequestFromForwardedHeaders(); UriComponents uriComponents = fromController(PersonControllerImpl.class).build(); - assertThat(uriComponents.toUriString(), startsWith("https://barfoo:8888")); + assertThat(uriComponents.toUriString()).startsWith("https://barfoo:8888"); } // SPR-16668 @@ -194,7 +188,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName(ControllerWithMethods.class, "methodWithPathVariable", "1").build(); - assertThat(uriComponents.toUriString(), is("http://localhost/something/1/foo")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/something/1/foo"); } @Test @@ -203,7 +197,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName( PersonsAddressesController.class, "getAddressesForCountry", "DE").buildAndExpand("1"); - assertThat(uriComponents.toUriString(), is("http://localhost/myapp/people/1/addresses/DE")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/myapp/people/1/addresses/DE"); } @Test @@ -212,7 +206,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName( ControllerWithMethods.class, "methodWithTwoPathVariables", 1, now).build(); - assertThat(uriComponents.getPath(), is("/something/1/foo/" + ISODateTimeFormat.date().print(now))); + assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo/" + ISODateTimeFormat.date().print(now)); } @Test @@ -220,31 +214,31 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName( ControllerWithMethods.class, "methodForNextPage", "1", 10, 5).build(); - assertThat(uriComponents.getPath(), is("/something/1/foo")); + assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo"); MultiValueMap queryParams = uriComponents.getQueryParams(); - assertThat(queryParams.get("limit"), contains("5")); - assertThat(queryParams.get("offset"), contains("10")); + assertThat(queryParams.get("limit")).contains("5"); + assertThat(queryParams.get("offset")).contains("10"); } @Test // SPR-12977 public void fromMethodNameWithBridgedMethod() { UriComponents uriComponents = fromMethodName(PersonCrudController.class, "get", (long) 42).build(); - assertThat(uriComponents.toUriString(), is("http://localhost/42")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/42"); } @Test // SPR-11391 public void fromMethodNameTypeLevelPathVariableWithoutArgumentValue() { UriComponents uriComponents = fromMethodName(UserContactController.class, "showCreate", 123).build(); - assertThat(uriComponents.getPath(), is("/user/123/contacts/create")); + assertThat(uriComponents.getPath()).isEqualTo("/user/123/contacts/create"); } @Test public void fromMethodNameNotMapped() { UriComponents uriComponents = fromMethodName(UnmappedController.class, "unmappedMethod").build(); - assertThat(uriComponents.toUriString(), is("http://localhost/")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/"); } @Test @@ -273,7 +267,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName(ControllerWithMethods.class, "methodWithOptionalParam", new Object[] {null}).build(); - assertThat(uriComponents.toUriString(), is("http://localhost/something/optional-param")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/something/optional-param"); } @Test // gh-22656 @@ -281,31 +275,31 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName(ControllerWithMethods.class, "methodWithOptionalNamedParam", Optional.of("foo")).build(); - assertThat(uriComponents.toUriString(), - is("http://localhost/something/optional-param-with-name?search=foo")); + assertThat(uriComponents.toUriString()) + .isEqualTo("http://localhost/something/optional-param-with-name?search=foo"); } @Test public void fromMethodNameWithMetaAnnotation() { UriComponents uriComponents = fromMethodName(MetaAnnotationController.class, "handleInput").build(); - assertThat(uriComponents.toUriString(), is("http://localhost/input")); + assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/input"); } @Test public void fromMethodCallPlain() { UriComponents uriComponents = fromMethodCall(on(ControllerWithMethods.class).myMethod(null)).build(); - assertThat(uriComponents.toUriString(), startsWith("http://localhost")); - assertThat(uriComponents.toUriString(), endsWith("/something/else")); + assertThat(uriComponents.toUriString()).startsWith("http://localhost"); + assertThat(uriComponents.toUriString()).endsWith("/something/else"); } @Test public void fromMethodCallOnSubclass() { UriComponents uriComponents = fromMethodCall(on(ExtendedController.class).myMethod(null)).build(); - assertThat(uriComponents.toUriString(), startsWith("http://localhost")); - assertThat(uriComponents.toUriString(), endsWith("/extended/else")); + assertThat(uriComponents.toUriString()).startsWith("http://localhost"); + assertThat(uriComponents.toUriString()).endsWith("/extended/else"); } @Test @@ -313,7 +307,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodCall( on(PersonsAddressesController.class).getAddressesForCountry("DE")).buildAndExpand(15); - assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses/DE")); + assertThat(uriComponents.toUriString()).endsWith("/people/15/addresses/DE"); } @Test @@ -321,8 +315,8 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodCall( on(ControllerWithMethods.class).methodWithPathVariable("1")).build(); - assertThat(uriComponents.toUriString(), startsWith("http://localhost")); - assertThat(uriComponents.toUriString(), endsWith("/something/1/foo")); + assertThat(uriComponents.toUriString()).startsWith("http://localhost"); + assertThat(uriComponents.toUriString()).endsWith("/something/1/foo"); } @Test @@ -330,11 +324,11 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodCall( on(ControllerWithMethods.class).methodForNextPage("1", 10, 5)).build(); - assertThat(uriComponents.getPath(), is("/something/1/foo")); + assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo"); MultiValueMap queryParams = uriComponents.getQueryParams(); - assertThat(queryParams.get("limit"), contains("5")); - assertThat(queryParams.get("offset"), contains("10")); + assertThat(queryParams.get("limit")).contains("5"); + assertThat(queryParams.get("offset")).contains("10"); } @Test @@ -342,11 +336,11 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodCall( on(ControllerWithMethods.class).methodWithMultiValueRequestParams("1", Arrays.asList(3, 7), 5)).build(); - assertThat(uriComponents.getPath(), is("/something/1/foo")); + assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo"); MultiValueMap queryParams = uriComponents.getQueryParams(); - assertThat(queryParams.get("limit"), contains("5")); - assertThat(queryParams.get("items"), containsInAnyOrder("3", "7")); + assertThat(queryParams.get("limit")).contains("5"); + assertThat(queryParams.get("items")).containsExactly("3", "7"); } @Test 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 7ad9b43ad2..c1892eb899 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 @@ -34,7 +34,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -85,7 +84,7 @@ import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.UriComponentsBuilder; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -373,7 +372,7 @@ public class RequestMappingHandlerAdapterIntegrationTests { assertNull(mav); assertEquals(HttpStatus.OK.value(), response.getStatus()); assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8")); - assertThat(response.getHeaderValues("Cache-Control"), Matchers.contains("max-age=3600")); + assertThat(response.getHeaderValues("Cache-Control")).containsExactly("max-age=3600"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java index 338248f94e..000b29a63e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java @@ -29,8 +29,7 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -104,18 +103,17 @@ public class AppCacheManifestTransformerTests { byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream()); String content = new String(bytes, "UTF-8"); - assertThat("should rewrite resource links", content, - containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css")); - assertThat("should rewrite resource links", content, - containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css")); - assertThat("should rewrite resource links", content, - containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js")); + assertThat(content).as("rewrite resource links") + .contains("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css") + .contains("/static/bar-11e16cf79faee7ac698c805cf28248d2.css") + .contains("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js"); - assertThat("should not rewrite external resources", content, containsString("//example.org/style.css")); - assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png")); + assertThat(content).as("not rewrite external resources") + .contains("//example.org/style.css") + .contains("http://example.org/image.png"); - assertThat("should generate fingerprint", content, - containsString("# Hash: 4bf0338bcbeb0a5b3a4ec9ed8864107d")); + assertThat(content).as("generate fingerprint") + .contains("# Hash: 4bf0338bcbeb0a5b3a4ec9ed8864107d"); } private Resource getResource(String filePath) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java index e55067fbc8..2d5c35469c 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 @@ -23,7 +23,6 @@ import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletResponse; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; @@ -42,9 +41,9 @@ import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; import org.springframework.web.servlet.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -187,7 +186,7 @@ public class ResourceHttpRequestHandlerTests { this.handler.handleRequest(this.request, this.response); assertEquals("no-cache", this.response.getHeader("Pragma")); - assertThat(this.response.getHeaderValues("Cache-Control"), Matchers.iterableWithSize(1)); + assertThat(this.response.getHeaderValues("Cache-Control")).hasSize(1); assertEquals("no-cache", this.response.getHeader("Cache-Control")); assertTrue(this.response.getDateHeader("Expires") <= System.currentTimeMillis()); assertTrue(this.response.containsHeader("Last-Modified")); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java index 639041a40a..901cd2c8a6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java @@ -21,7 +21,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; @@ -34,7 +33,7 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -148,7 +147,7 @@ public class ResourceUrlProviderTests { context.refresh(); ResourceUrlProvider urlProviderBean = context.getBean(ResourceUrlProvider.class); - assertThat(urlProviderBean.getHandlerMap(), Matchers.hasKey("/resources/**")); + assertThat(urlProviderBean.getHandlerMap()).containsKey("/resources/**"); assertFalse(urlProviderBean.isAutodetect()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java index ae6264d0a1..a8e69442a4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java @@ -21,8 +21,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; @@ -30,9 +28,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.given; @@ -158,7 +154,7 @@ public class VersionResourceResolverTests { Resource actual = this.resolver.resolveResourceInternal(request, versionFile, this.locations, this.chain); assertEquals(expected.getFilename(), actual.getFilename()); verify(this.versionStrategy, times(1)).getResourceVersion(expected); - assertThat(actual, instanceOf(HttpResource.class)); + assertThat(actual).isInstanceOf(HttpResource.class); assertEquals("\"" + version + "\"", ((HttpResource)actual).getResponseHeaders().getETag()); } @@ -183,19 +179,18 @@ public class VersionResourceResolverTests { this.resolver.addFixedVersionStrategy("fixedversion", "/js/**", "/css/**", "/fixedversion/css/**"); - Matcher matcher = Matchers.instanceOf(FixedVersionStrategy.class); - assertThat(this.resolver.getStrategyMap().size(), is(4)); - assertThat(this.resolver.getStrategyForPath("js/something.js"), matcher); - assertThat(this.resolver.getStrategyForPath("fixedversion/js/something.js"), matcher); - assertThat(this.resolver.getStrategyForPath("css/something.css"), matcher); - assertThat(this.resolver.getStrategyForPath("fixedversion/css/something.css"), matcher); + assertThat(this.resolver.getStrategyMap()).hasSize(4); + assertThat(this.resolver.getStrategyForPath("js/something.js")).isInstanceOf(FixedVersionStrategy.class); + assertThat(this.resolver.getStrategyForPath("fixedversion/js/something.js")).isInstanceOf(FixedVersionStrategy.class); + assertThat(this.resolver.getStrategyForPath("css/something.css")).isInstanceOf(FixedVersionStrategy.class); + assertThat(this.resolver.getStrategyForPath("fixedversion/css/something.css")).isInstanceOf(FixedVersionStrategy.class); } @Test // SPR-15372 public void resolveUrlPathNoVersionStrategy() throws Exception { given(this.chain.resolveUrlPath("/foo.css", this.locations)).willReturn("/foo.css"); String resolved = this.resolver.resolveUrlPathInternal("/foo.css", this.locations, this.chain); - assertThat(resolved, is("/foo.css")); + assertThat(resolved).isEqualTo("/foo.css"); } 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 815858083c..728d66dc19 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 @@ -30,8 +30,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockPageContext; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -55,7 +54,7 @@ public class UrlTagTests extends AbstractTagTests { @Test public void paramSupport() { - assertThat(tag, instanceOf(ParamAware.class)); + assertThat(tag).isInstanceOf(ParamAware.class); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java index 2e0ec258cb..1df8bb0efc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java @@ -32,9 +32,8 @@ import org.springframework.web.context.support.ServletContextResource; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.View; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -88,7 +87,7 @@ public class ResourceBundleViewResolverTests { @Test public void debugViewEnglish() throws Exception { View v = rb.resolveViewName("debugView", Locale.ENGLISH); - assertThat(v, instanceOf(InternalResourceView.class)); + assertThat(v).isInstanceOf(InternalResourceView.class); InternalResourceView jv = (InternalResourceView) v; assertEquals("debugView must have correct URL", "jsp/debug/debug.jsp", jv.getUrl()); @@ -103,7 +102,7 @@ public class ResourceBundleViewResolverTests { @Test public void debugViewFrench() throws Exception { View v = rb.resolveViewName("debugView", Locale.FRENCH); - assertThat(v, instanceOf(InternalResourceView.class)); + assertThat(v).isInstanceOf(InternalResourceView.class); InternalResourceView jv = (InternalResourceView) v; assertEquals("French debugView must have correct URL", "jsp/debug/deboug.jsp", jv.getUrl()); assertEquals("Correct overridden (XML) content type", "text/xml;charset=ISO-8859-1", jv.getContentType()); @@ -119,7 +118,7 @@ public class ResourceBundleViewResolverTests { rb.setApplicationContext(wac); View v = rb.resolveViewName("debugView", Locale.FRENCH); - assertThat(v, instanceOf(InternalResourceView.class)); + assertThat(v).isInstanceOf(InternalResourceView.class); InternalResourceView jv = (InternalResourceView) v; assertEquals("French debugView must have correct URL", "jsp/debug/deboug.jsp", jv.getUrl()); assertEquals("Correct overridden (XML) content type", "text/xml;charset=ISO-8859-1", jv.getContentType()); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/AtomFeedViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/AtomFeedViewTests.java index d57bd20cd6..e0e0c446a9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/AtomFeedViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/AtomFeedViewTests.java @@ -27,12 +27,12 @@ import com.rometools.rome.feed.atom.Content; import com.rometools.rome.feed.atom.Entry; import com.rometools.rome.feed.atom.Feed; import org.junit.Test; -import org.xmlunit.matchers.CompareMatcher; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import org.springframework.tests.XmlContent; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -56,12 +56,9 @@ public class AtomFeedViewTests { String expected = "" + "Test Feed" + "2This is entry 2" + "1This is entry 1" + ""; - assertThat(response.getContentAsString(), isSimilarTo(expected)); + assertThat(XmlContent.of(response.getContentAsString())).isSimilarToIgnoringWhitespace(expected); } - private static CompareMatcher isSimilarTo(String content) { - return CompareMatcher.isSimilarTo(content).ignoreWhitespace(); - } private static class MyAtomFeedView extends AbstractAtomFeedView { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/RssFeedViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/RssFeedViewTests.java index 475c44e9f4..ee90d515fd 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/RssFeedViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/RssFeedViewTests.java @@ -30,10 +30,10 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import org.springframework.tests.XmlContent; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** * @author Arjen Poutsma @@ -61,7 +61,7 @@ public class RssFeedViewTests { "2This is entry 2" + "1This is entry 1" + ""; - assertThat(response.getContentAsString(), isSimilarTo(expected).ignoreWhitespace()); + assertThat(XmlContent.of(response.getContentAsString())).isSimilarToIgnoringWhitespace(expected); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java index f7d3350218..4c205e119a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java @@ -34,9 +34,8 @@ import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.ui.freemarker.SpringTemplateLoader; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -88,7 +87,7 @@ public class FreeMarkerConfigurerTests { } }); fcfb.afterPropertiesSet(); - assertThat(fcfb.getObject(), instanceOf(Configuration.class)); + assertThat(fcfb.getObject()).isInstanceOf(Configuration.class); Configuration fc = fcfb.getObject(); Template ft = fc.getTemplate("test"); assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap())); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupConfigurerTests.java index a6fd7dc4b8..776ed40028 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupConfigurerTests.java @@ -18,21 +18,19 @@ package org.springframework.web.servlet.view.groovy; import java.net.URL; import java.net.URLClassLoader; -import java.util.Arrays; import java.util.Locale; import groovy.text.TemplateEngine; import groovy.text.markup.MarkupTemplateEngine; import groovy.text.markup.TemplateConfiguration; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.support.StaticApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -112,19 +110,19 @@ public class GroovyMarkupConfigurerTests { ClassLoader classLoader = this.configurer.createTemplateClassLoader(); assertNotNull(classLoader); URLClassLoader urlClassLoader = (URLClassLoader) classLoader; - assertThat(Arrays.asList(urlClassLoader.getURLs()), Matchers.hasSize(1)); - assertThat(Arrays.asList(urlClassLoader.getURLs()).get(0).toString(), - Matchers.endsWith("org/springframework/web/servlet/view/groovy/")); + assertThat(urlClassLoader.getURLs()).hasSize(1); + assertThat(urlClassLoader.getURLs()[0].toString()) + .endsWith("org/springframework/web/servlet/view/groovy/"); this.configurer.setResourceLoaderPath(RESOURCE_LOADER_PATH + ",classpath:org/springframework/web/servlet/view/"); classLoader = this.configurer.createTemplateClassLoader(); assertNotNull(classLoader); urlClassLoader = (URLClassLoader) classLoader; - assertThat(Arrays.asList(urlClassLoader.getURLs()), Matchers.hasSize(2)); - assertThat(Arrays.asList(urlClassLoader.getURLs()).get(0).toString(), - Matchers.endsWith("org/springframework/web/servlet/view/groovy/")); - assertThat(Arrays.asList(urlClassLoader.getURLs()).get(1).toString(), - Matchers.endsWith("org/springframework/web/servlet/view/")); + assertThat(urlClassLoader.getURLs()).hasSize(2); + assertThat(urlClassLoader.getURLs()[0].toString()) + .endsWith("org/springframework/web/servlet/view/groovy/"); + assertThat(urlClassLoader.getURLs()[1].toString()) + .endsWith("org/springframework/web/servlet/view/"); } private class TestTemplateEngine extends MarkupTemplateEngine { @@ -145,7 +143,7 @@ public class GroovyMarkupConfigurerTests { LocaleContextHolder.setLocale(Locale.GERMANY); URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl"); assertNotNull(url); - assertThat(url.getPath(), Matchers.containsString("i18n_de_DE.tpl")); + assertThat(url.getPath()).contains("i18n_de_DE.tpl"); } @Test @@ -153,7 +151,7 @@ public class GroovyMarkupConfigurerTests { LocaleContextHolder.setLocale(Locale.FRANCE); URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl"); assertNotNull(url); - assertThat(url.getPath(), Matchers.containsString("i18n_fr.tpl")); + assertThat(url.getPath()).contains("i18n_fr.tpl"); } @Test @@ -161,7 +159,7 @@ public class GroovyMarkupConfigurerTests { LocaleContextHolder.setLocale(Locale.US); URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl"); assertNotNull(url); - assertThat(url.getPath(), Matchers.containsString("i18n.tpl")); + assertThat(url.getPath()).contains("i18n.tpl"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupViewTests.java index f9df594424..b5a160cc18 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/groovy/GroovyMarkupViewTests.java @@ -26,7 +26,6 @@ import groovy.text.Template; import groovy.text.TemplateEngine; import groovy.text.markup.MarkupTemplateEngine; import groovy.text.markup.TemplateConfiguration; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; @@ -41,8 +40,8 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.WebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -135,7 +134,7 @@ public class GroovyMarkupViewTests { Map model = new HashMap<>(); model.put("name", "Spring"); MockHttpServletResponse response = renderViewWithModel("test.tpl", model, Locale.US); - assertThat(response.getContentAsString(), Matchers.containsString("

Hello Spring

")); + assertThat(response.getContentAsString()).contains("

Hello Spring

"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java index 1ce38bb772..3745ec4f57 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java @@ -52,9 +52,7 @@ import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.View; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -322,8 +320,8 @@ public class MappingJackson2JsonViewTests { String content = response.getContentAsString(); assertTrue(content.length() > 0); assertEquals(content.length(), response.getContentLength()); - assertThat(content, containsString("\"property1\":\"value\"")); - assertThat(content, not(containsString("\"property2\":\"value\""))); + assertThat(content).contains("\"property1\":\"value\""); + assertThat(content).doesNotContain("\"property2\":\"value\""); assertFalse(content.contains(FilterProvider.class.getName())); } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/TextMessageTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/TextMessageTests.java index 1a61aab0d7..97bd2652b6 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/TextMessageTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/TextMessageTests.java @@ -16,10 +16,10 @@ package org.springframework.web.socket; -import org.hamcrest.Matchers; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Test fixture for {@link TextMessage}. @@ -33,16 +33,16 @@ public class TextMessageTests { public void toStringWithAscii() { String expected = "foo,bar"; TextMessage actual = new TextMessage(expected); - assertThat(actual.getPayload(), Matchers.is(expected)); - assertThat(actual.toString(), Matchers.containsString(expected)); + assertThat(actual.getPayload()).isEqualTo(expected); + assertThat(actual.toString()).contains(expected); } @Test public void toStringWithMultibyteString() { String expected = "\u3042\u3044\u3046\u3048\u304a"; TextMessage actual = new TextMessage(expected); - assertThat(actual.getPayload(), Matchers.is(expected)); - assertThat(actual.toString(), Matchers.containsString(expected)); + assertThat(actual.getPayload()).isEqualTo(expected); + assertThat(actual.toString()).contains(expected); } } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/WebSocketExtensionTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/WebSocketExtensionTests.java index 64ff91b4a0..42edde179f 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/WebSocketExtensionTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/WebSocketExtensionTests.java @@ -18,10 +18,9 @@ package org.springframework.web.socket; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; /** @@ -33,7 +32,7 @@ public class WebSocketExtensionTests { @Test public void parseHeaderSingle() { List extensions = WebSocketExtension.parseExtensions("x-test-extension ; foo=bar ; bar=baz"); - assertThat(extensions, Matchers.hasSize(1)); + assertThat(extensions).hasSize(1); WebSocketExtension extension = extensions.get(0); assertEquals("x-test-extension", extension.getName()); @@ -45,9 +44,8 @@ public class WebSocketExtensionTests { @Test public void parseHeaderMultiple() { List extensions = WebSocketExtension.parseExtensions("x-foo-extension, x-bar-extension"); - assertThat(extensions, Matchers.hasSize(2)); - assertEquals("x-foo-extension", extensions.get(0).getName()); - assertEquals("x-bar-extension", extensions.get(1).getName()); + assertThat(extensions.stream().map(WebSocketExtension::getName)) + .containsExactly("x-foo-extension", "x-bar-extension"); } } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java index 856bdc5118..c44ed07b83 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java @@ -38,11 +38,12 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.socket.ContextLoaderTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; + + + /** * Test for {@link org.springframework.web.socket.adapter.standard.ConvertingEncoderDecoderSupport}. @@ -81,7 +82,7 @@ public class ConvertingEncoderDecoderSupportTests { @Test public void encodeToText() throws Exception { - assertThat(new MyTextEncoder().encode(myType), equalTo(CONVERTED_TEXT)); + assertThat(new MyTextEncoder().encode(myType)).isEqualTo(CONVERTED_TEXT); } @Test @@ -94,8 +95,8 @@ public class ConvertingEncoderDecoderSupportTests { @Test public void encodeToBinary() throws Exception { - assertThat(new MyBinaryEncoder().encode(myType).array(), - equalTo(CONVERTED_BYTES.array())); + assertThat(new MyBinaryEncoder().encode(myType).array()) + .isEqualTo(CONVERTED_BYTES.array()); } @Test @@ -109,15 +110,15 @@ public class ConvertingEncoderDecoderSupportTests { @Test public void decodeFromText() throws Exception { Decoder.Text decoder = new MyTextDecoder(); - assertThat(decoder.willDecode(CONVERTED_TEXT), is(true)); - assertThat(decoder.decode(CONVERTED_TEXT), equalTo(myType)); + assertThat(decoder.willDecode(CONVERTED_TEXT)).isTrue(); + assertThat(decoder.decode(CONVERTED_TEXT)).isEqualTo(myType); } @Test public void decodeFromTextCannotConvert() throws Exception { setup(NoConvertersConfig.class); Decoder.Text decoder = new MyTextDecoder(); - assertThat(decoder.willDecode(CONVERTED_TEXT), is(false)); + assertThat(decoder.willDecode(CONVERTED_TEXT)).isFalse(); assertThatExceptionOfType(DecodeException.class).isThrownBy(() -> decoder.decode(CONVERTED_TEXT)) .withCauseInstanceOf(ConverterNotFoundException.class); @@ -126,15 +127,15 @@ public class ConvertingEncoderDecoderSupportTests { @Test public void decodeFromBinary() throws Exception { Decoder.Binary decoder = new MyBinaryDecoder(); - assertThat(decoder.willDecode(CONVERTED_BYTES), is(true)); - assertThat(decoder.decode(CONVERTED_BYTES), equalTo(myType)); + assertThat(decoder.willDecode(CONVERTED_BYTES)).isTrue(); + assertThat(decoder.decode(CONVERTED_BYTES)).isEqualTo(myType); } @Test public void decodeFromBinaryCannotConvert() throws Exception { setup(NoConvertersConfig.class); Decoder.Binary decoder = new MyBinaryDecoder(); - assertThat(decoder.willDecode(CONVERTED_BYTES), is(false)); + assertThat(decoder.willDecode(CONVERTED_BYTES)).isFalse(); assertThatExceptionOfType(DecodeException.class).isThrownBy(() -> decoder.decode(CONVERTED_BYTES)) .withCauseInstanceOf(ConverterNotFoundException.class); @@ -144,21 +145,21 @@ public class ConvertingEncoderDecoderSupportTests { public void encodeAndDecodeText() throws Exception { MyTextEncoderDecoder encoderDecoder = new MyTextEncoderDecoder(); String encoded = encoderDecoder.encode(myType); - assertThat(encoderDecoder.decode(encoded), equalTo(myType)); + assertThat(encoderDecoder.decode(encoded)).isEqualTo(myType); } @Test public void encodeAndDecodeBytes() throws Exception { MyBinaryEncoderDecoder encoderDecoder = new MyBinaryEncoderDecoder(); ByteBuffer encoded = encoderDecoder.encode(myType); - assertThat(encoderDecoder.decode(encoded), equalTo(myType)); + assertThat(encoderDecoder.decode(encoded)).isEqualTo(myType); } @Test public void autowiresIntoEncoder() throws Exception { WithAutowire withAutowire = new WithAutowire(); withAutowire.init(null); - assertThat(withAutowire.config, equalTo(applicationContext.getBean(Config.class))); + assertThat(withAutowire.config).isEqualTo(applicationContext.getBean(Config.class)); } @Test diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java index 37ce6aaae2..6e66ef5959 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java @@ -60,11 +60,7 @@ import org.springframework.web.socket.sockjs.transport.handler.XhrPollingTranspo import org.springframework.web.socket.sockjs.transport.handler.XhrReceivingTransportHandler; import org.springframework.web.socket.sockjs.transport.handler.XhrStreamingTransportHandler; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -89,14 +85,14 @@ public class HandlersBeanDefinitionParserTests { Map handlersMap = this.appContext.getBeansOfType(HandlerMapping.class); assertNotNull(handlersMap); - assertThat(handlersMap.values(), hasSize(2)); + assertThat(handlersMap).hasSize(2); for (HandlerMapping hm : handlersMap.values()) { assertTrue(hm instanceof SimpleUrlHandlerMapping); SimpleUrlHandlerMapping shm = (SimpleUrlHandlerMapping) hm; if (shm.getUrlMap().keySet().contains("/foo")) { - assertThat(shm.getUrlMap().keySet(), contains("/foo", "/bar")); + assertThat(shm.getUrlMap()).containsOnlyKeys("/foo", "/bar"); WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler) shm.getUrlMap().get("/foo"); assertNotNull(handler); unwrapAndCheckDecoratedHandlerType(handler.getWebSocketHandler(), FooWebSocketHandler.class); @@ -107,7 +103,7 @@ public class HandlersBeanDefinitionParserTests { assertTrue(handler.getHandshakeInterceptors().get(0) instanceof OriginHandshakeInterceptor); } else { - assertThat(shm.getUrlMap().keySet(), contains("/test")); + assertThat(shm.getUrlMap()).containsOnlyKeys("/test"); WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler) shm.getUrlMap().get("/test"); assertNotNull(handler); unwrapAndCheckDecoratedHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class); @@ -139,8 +135,8 @@ public class HandlersBeanDefinitionParserTests { assertNotNull(handshakeHandler); assertTrue(handshakeHandler instanceof TestHandshakeHandler); List interceptors = handler.getHandshakeInterceptors(); - assertThat(interceptors, contains(instanceOf(FooTestInterceptor.class), - instanceOf(BarTestInterceptor.class), instanceOf(OriginHandshakeInterceptor.class))); + assertThat(interceptors).extracting("class") + .containsExactlyInAnyOrder(FooTestInterceptor.class, BarTestInterceptor.class, OriginHandshakeInterceptor.class); handler = (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/test"); assertNotNull(handler); @@ -149,8 +145,8 @@ public class HandlersBeanDefinitionParserTests { assertNotNull(handshakeHandler); assertTrue(handshakeHandler instanceof TestHandshakeHandler); interceptors = handler.getHandshakeInterceptors(); - assertThat(interceptors, contains(instanceOf(FooTestInterceptor.class), - instanceOf(BarTestInterceptor.class), instanceOf(OriginHandshakeInterceptor.class))); + assertThat(interceptors).extracting("class") + .containsExactlyInAnyOrder(FooTestInterceptor.class, BarTestInterceptor.class, OriginHandshakeInterceptor.class); } @Test @@ -174,27 +170,27 @@ public class HandlersBeanDefinitionParserTests { assertSame(testSockJsService, sockJsService); - assertThat(sockJsService, instanceOf(DefaultSockJsService.class)); + assertThat(sockJsService).isInstanceOf(DefaultSockJsService.class); DefaultSockJsService defaultSockJsService = (DefaultSockJsService) sockJsService; - assertThat(defaultSockJsService.getTaskScheduler(), instanceOf(ThreadPoolTaskScheduler.class)); + assertThat(defaultSockJsService.getTaskScheduler()).isInstanceOf(ThreadPoolTaskScheduler.class); assertFalse(defaultSockJsService.shouldSuppressCors()); Map handlerMap = defaultSockJsService.getTransportHandlers(); - assertThat(handlerMap.values(), - containsInAnyOrder( - instanceOf(XhrPollingTransportHandler.class), - instanceOf(XhrReceivingTransportHandler.class), - instanceOf(XhrStreamingTransportHandler.class), - instanceOf(EventSourceTransportHandler.class), - instanceOf(HtmlFileTransportHandler.class), - instanceOf(WebSocketTransportHandler.class))); + assertThat(handlerMap.values()).extracting("class") + .containsExactlyInAnyOrder( + XhrPollingTransportHandler.class, + XhrReceivingTransportHandler.class, + XhrStreamingTransportHandler.class, + EventSourceTransportHandler.class, + HtmlFileTransportHandler.class, + WebSocketTransportHandler.class); WebSocketTransportHandler handler = (WebSocketTransportHandler) handlerMap.get(TransportType.WEBSOCKET); assertEquals(TestHandshakeHandler.class, handler.getHandshakeHandler().getClass()); List interceptors = defaultSockJsService.getHandshakeInterceptors(); - assertThat(interceptors, contains(instanceOf(FooTestInterceptor.class), - instanceOf(BarTestInterceptor.class), instanceOf(OriginHandshakeInterceptor.class))); + assertThat(interceptors).extracting("class") + .containsExactlyInAnyOrder(FooTestInterceptor.class, BarTestInterceptor.class, OriginHandshakeInterceptor.class); } @Test @@ -211,13 +207,11 @@ public class HandlersBeanDefinitionParserTests { SockJsService sockJsService = handler.getSockJsService(); assertNotNull(sockJsService); - assertThat(sockJsService, instanceOf(TransportHandlingSockJsService.class)); + assertThat(sockJsService).isInstanceOf(TransportHandlingSockJsService.class); TransportHandlingSockJsService transportService = (TransportHandlingSockJsService) sockJsService; - assertThat(transportService.getTaskScheduler(), instanceOf(TestTaskScheduler.class)); - assertThat(transportService.getTransportHandlers().values(), - containsInAnyOrder( - instanceOf(XhrPollingTransportHandler.class), - instanceOf(XhrStreamingTransportHandler.class))); + assertThat(transportService.getTaskScheduler()).isInstanceOf(TestTaskScheduler.class); + assertThat(transportService.getTransportHandlers().values()).extracting("class") + .containsExactlyInAnyOrder(XhrPollingTransportHandler.class, XhrStreamingTransportHandler.class); assertEquals("testSockJsService", transportService.getName()); assertFalse(transportService.isWebSocketEnabled()); @@ -230,7 +224,7 @@ public class HandlersBeanDefinitionParserTests { assertEquals(TestMessageCodec.class, transportService.getMessageCodec().getClass()); List interceptors = transportService.getHandshakeInterceptors(); - assertThat(interceptors, contains(instanceOf(OriginHandshakeInterceptor.class))); + assertThat(interceptors).extracting("class").containsExactly(OriginHandshakeInterceptor.class); assertTrue(transportService.shouldSuppressCors()); assertTrue(transportService.getAllowedOrigins().contains("https://mydomain1.com")); assertTrue(transportService.getAllowedOrigins().contains("https://mydomain2.com")); diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java index 6b63353778..b155899058 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledThreadPoolExecutor; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; @@ -90,10 +89,8 @@ import org.springframework.web.socket.sockjs.transport.TransportType; import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService; import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -120,35 +117,34 @@ public class MessageBrokerBeanDefinitionParserTests { loadBeanDefinitions("websocket-config-broker-simple.xml"); HandlerMapping hm = this.appContext.getBean(HandlerMapping.class); - assertThat(hm, Matchers.instanceOf(SimpleUrlHandlerMapping.class)); + assertThat(hm).isInstanceOf(SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping suhm = (SimpleUrlHandlerMapping) hm; - assertThat(suhm.getUrlMap().keySet(), Matchers.hasSize(4)); - assertThat(suhm.getUrlMap().values(), Matchers.hasSize(4)); + assertThat(suhm.getUrlMap()).hasSize(4); HttpRequestHandler httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/foo"); assertNotNull(httpRequestHandler); - assertThat(httpRequestHandler, Matchers.instanceOf(WebSocketHttpRequestHandler.class)); + assertThat(httpRequestHandler).isInstanceOf(WebSocketHttpRequestHandler.class); WebSocketHttpRequestHandler wsHttpRequestHandler = (WebSocketHttpRequestHandler) httpRequestHandler; HandshakeHandler handshakeHandler = wsHttpRequestHandler.getHandshakeHandler(); assertNotNull(handshakeHandler); assertTrue(handshakeHandler instanceof TestHandshakeHandler); List interceptors = wsHttpRequestHandler.getHandshakeInterceptors(); - assertThat(interceptors, contains(instanceOf(FooTestInterceptor.class), - instanceOf(BarTestInterceptor.class), instanceOf(OriginHandshakeInterceptor.class))); + assertThat(interceptors).extracting("class").containsExactly(FooTestInterceptor.class, + BarTestInterceptor.class, OriginHandshakeInterceptor.class); WebSocketSession session = new TestWebSocketSession("id"); wsHttpRequestHandler.getWebSocketHandler().afterConnectionEstablished(session); assertEquals(true, session.getAttributes().get("decorated")); WebSocketHandler wsHandler = wsHttpRequestHandler.getWebSocketHandler(); - assertThat(wsHandler, Matchers.instanceOf(ExceptionWebSocketHandlerDecorator.class)); + assertThat(wsHandler).isInstanceOf(ExceptionWebSocketHandlerDecorator.class); wsHandler = ((ExceptionWebSocketHandlerDecorator) wsHandler).getDelegate(); - assertThat(wsHandler, Matchers.instanceOf(LoggingWebSocketHandlerDecorator.class)); + assertThat(wsHandler).isInstanceOf(LoggingWebSocketHandlerDecorator.class); wsHandler = ((LoggingWebSocketHandlerDecorator) wsHandler).getDelegate(); - assertThat(wsHandler, Matchers.instanceOf(TestWebSocketHandlerDecorator.class)); + assertThat(wsHandler).isInstanceOf(TestWebSocketHandlerDecorator.class); wsHandler = ((TestWebSocketHandlerDecorator) wsHandler).getDelegate(); - assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class)); + assertThat(wsHandler).isInstanceOf(SubProtocolWebSocketHandler.class); assertSame(wsHandler, this.appContext.getBean(MessageBrokerBeanDefinitionParser.WEB_SOCKET_HANDLER_BEAN_NAME)); SubProtocolWebSocketHandler subProtocolWsHandler = (SubProtocolWebSocketHandler) wsHandler; @@ -168,20 +164,20 @@ public class MessageBrokerBeanDefinitionParserTests { httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/test/**"); assertNotNull(httpRequestHandler); - assertThat(httpRequestHandler, Matchers.instanceOf(SockJsHttpRequestHandler.class)); + assertThat(httpRequestHandler).isInstanceOf(SockJsHttpRequestHandler.class); SockJsHttpRequestHandler sockJsHttpRequestHandler = (SockJsHttpRequestHandler) httpRequestHandler; wsHandler = unwrapWebSocketHandler(sockJsHttpRequestHandler.getWebSocketHandler()); assertNotNull(wsHandler); - assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class)); + assertThat(wsHandler).isInstanceOf(SubProtocolWebSocketHandler.class); assertNotNull(sockJsHttpRequestHandler.getSockJsService()); - assertThat(sockJsHttpRequestHandler.getSockJsService(), Matchers.instanceOf(DefaultSockJsService.class)); + assertThat(sockJsHttpRequestHandler.getSockJsService()).isInstanceOf(DefaultSockJsService.class); DefaultSockJsService defaultSockJsService = (DefaultSockJsService) sockJsHttpRequestHandler.getSockJsService(); WebSocketTransportHandler wsTransportHandler = (WebSocketTransportHandler) defaultSockJsService .getTransportHandlers().get(TransportType.WEBSOCKET); assertNotNull(wsTransportHandler.getHandshakeHandler()); - assertThat(wsTransportHandler.getHandshakeHandler(), Matchers.instanceOf(TestHandshakeHandler.class)); + assertThat(wsTransportHandler.getHandshakeHandler()).isInstanceOf(TestHandshakeHandler.class); assertFalse(defaultSockJsService.shouldSuppressCors()); ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler) defaultSockJsService.getTaskScheduler(); @@ -190,8 +186,8 @@ public class MessageBrokerBeanDefinitionParserTests { assertTrue(executor.getRemoveOnCancelPolicy()); interceptors = defaultSockJsService.getHandshakeInterceptors(); - assertThat(interceptors, contains(instanceOf(FooTestInterceptor.class), - instanceOf(BarTestInterceptor.class), instanceOf(OriginHandshakeInterceptor.class))); + assertThat(interceptors).extracting("class").containsExactly(FooTestInterceptor.class, + BarTestInterceptor.class, OriginHandshakeInterceptor.class); assertTrue(defaultSockJsService.getAllowedOrigins().contains("https://mydomain3.com")); assertTrue(defaultSockJsService.getAllowedOrigins().contains("https://mydomain4.com")); @@ -201,7 +197,7 @@ public class MessageBrokerBeanDefinitionParserTests { UserDestinationResolver userDestResolver = this.appContext.getBean(UserDestinationResolver.class); assertNotNull(userDestResolver); - assertThat(userDestResolver, Matchers.instanceOf(DefaultUserDestinationResolver.class)); + assertThat(userDestResolver).isInstanceOf(DefaultUserDestinationResolver.class); DefaultUserDestinationResolver defaultUserDestResolver = (DefaultUserDestinationResolver) userDestResolver; assertEquals("/personal/", defaultUserDestResolver.getDestinationPrefix()); @@ -246,25 +242,24 @@ public class MessageBrokerBeanDefinitionParserTests { HandlerMapping hm = this.appContext.getBean(HandlerMapping.class); assertNotNull(hm); - assertThat(hm, Matchers.instanceOf(SimpleUrlHandlerMapping.class)); + assertThat(hm).isInstanceOf(SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping suhm = (SimpleUrlHandlerMapping) hm; - assertThat(suhm.getUrlMap().keySet(), Matchers.hasSize(1)); - assertThat(suhm.getUrlMap().values(), Matchers.hasSize(1)); + assertThat(suhm.getUrlMap()).hasSize(1); assertEquals(2, suhm.getOrder()); HttpRequestHandler httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/foo/**"); assertNotNull(httpRequestHandler); - assertThat(httpRequestHandler, Matchers.instanceOf(SockJsHttpRequestHandler.class)); + assertThat(httpRequestHandler).isInstanceOf(SockJsHttpRequestHandler.class); SockJsHttpRequestHandler sockJsHttpRequestHandler = (SockJsHttpRequestHandler) httpRequestHandler; WebSocketHandler wsHandler = unwrapWebSocketHandler(sockJsHttpRequestHandler.getWebSocketHandler()); assertNotNull(wsHandler); - assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class)); + assertThat(wsHandler).isInstanceOf(SubProtocolWebSocketHandler.class); assertNotNull(sockJsHttpRequestHandler.getSockJsService()); UserDestinationResolver userDestResolver = this.appContext.getBean(UserDestinationResolver.class); assertNotNull(userDestResolver); - assertThat(userDestResolver, Matchers.instanceOf(DefaultUserDestinationResolver.class)); + assertThat(userDestResolver).isInstanceOf(DefaultUserDestinationResolver.class); DefaultUserDestinationResolver defaultUserDestResolver = (DefaultUserDestinationResolver) userDestResolver; assertEquals("/user/", defaultUserDestResolver.getDestinationPrefix()); @@ -279,7 +274,7 @@ public class MessageBrokerBeanDefinitionParserTests { assertEquals("spring.io", messageBroker.getVirtualHost()); assertEquals(5000, messageBroker.getSystemHeartbeatReceiveInterval()); assertEquals(5000, messageBroker.getSystemHeartbeatSendInterval()); - assertThat(messageBroker.getDestinationPrefixes(), Matchers.containsInAnyOrder("/topic","/queue")); + assertThat(messageBroker.getDestinationPrefixes()).containsExactlyInAnyOrder("/topic","/queue"); assertTrue(messageBroker.isPreservePublishOrder()); List> subscriberTypes = Arrays.asList(SimpAnnotationMethodMessageHandler.class, @@ -351,10 +346,10 @@ public class MessageBrokerBeanDefinitionParserTests { assertEquals("/personal/", simpMessagingTemplate.getUserDestinationPrefix()); List converters = compositeMessageConverter.getConverters(); - assertThat(converters.size(), Matchers.is(3)); - assertThat(converters.get(0), Matchers.instanceOf(StringMessageConverter.class)); - assertThat(converters.get(1), Matchers.instanceOf(ByteArrayMessageConverter.class)); - assertThat(converters.get(2), Matchers.instanceOf(MappingJackson2MessageConverter.class)); + assertThat(converters).hasSize(3); + assertThat(converters.get(0)).isInstanceOf(StringMessageConverter.class); + assertThat(converters.get(1)).isInstanceOf(ByteArrayMessageConverter.class); + assertThat(converters.get(2)).isInstanceOf(MappingJackson2MessageConverter.class); ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver(); assertEquals(MimeTypeUtils.APPLICATION_JSON, ((DefaultContentTypeResolver) resolver).getDefaultMimeType()); @@ -375,7 +370,7 @@ public class MessageBrokerBeanDefinitionParserTests { Validator validator = annotationMethodMessageHandler.getValidator(); assertNotNull(validator); assertSame(this.appContext.getBean("myValidator"), validator); - assertThat(validator, Matchers.instanceOf(TestValidator.class)); + assertThat(validator).isInstanceOf(TestValidator.class); List> subscriberTypes = Arrays.asList(SimpAnnotationMethodMessageHandler.class, UserDestinationMessageHandler.class, SimpleBrokerMessageHandler.class); diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/handler/WebSocketHttpHeadersTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/handler/WebSocketHttpHeadersTests.java index b92eea0a72..98d0067cf7 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/handler/WebSocketHttpHeadersTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/handler/WebSocketHttpHeadersTests.java @@ -19,14 +19,14 @@ package org.springframework.web.socket.handler; import java.util.ArrayList; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.socket.WebSocketHttpHeaders; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit tests for WebSocketHttpHeaders. @@ -50,7 +50,7 @@ public class WebSocketHttpHeadersTests { this.headers.put(WebSocketHttpHeaders.SEC_WEBSOCKET_EXTENSIONS, extensions); List parsedExtensions = this.headers.getSecWebSocketExtensions(); - assertThat(parsedExtensions, Matchers.hasSize(3)); + assertThat(parsedExtensions).hasSize(3); } } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java index 446be628f4..42011fff14 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java @@ -59,8 +59,7 @@ import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.handler.TestWebSocketSession; import org.springframework.web.socket.sockjs.transport.SockJsSession; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -492,7 +491,7 @@ public class StompSubProtocolHandlerTests { @Override public boolean send(Message message) { SimpAttributes simpAttributes = SimpAttributesContextHolder.currentAttributes(); - assertThat(simpAttributes.getAttribute("name"), is("value")); + assertThat(simpAttributes.getAttribute("name")).isEqualTo("value"); return true; } @Override diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/messaging/WebSocketStompClientIntegrationTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/messaging/WebSocketStompClientIntegrationTests.java index 0c8da06de8..9612730b39 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/messaging/WebSocketStompClientIntegrationTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/messaging/WebSocketStompClientIntegrationTests.java @@ -48,8 +48,7 @@ import org.springframework.web.socket.server.RequestUpgradeStrategy; import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -121,7 +120,7 @@ public class WebSocketStompClientIntegrationTests { this.stompClient.connect(url, testHandler); assertTrue(testHandler.awaitForMessageCount(1, 5000)); - assertThat(testHandler.getReceived(), containsInAnyOrder("payload")); + assertThat(testHandler.getReceived()).containsExactly("payload"); } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/ClientSockJsSessionTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/ClientSockJsSessionTests.java index 66f036a9be..19f1aa0270 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/ClientSockJsSessionTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/ClientSockJsSessionTests.java @@ -34,11 +34,8 @@ import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec; import org.springframework.web.socket.sockjs.frame.SockJsFrame; import org.springframework.web.socket.sockjs.transport.TransportType; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -76,11 +73,11 @@ public class ClientSockJsSessionTests { @Test public void handleFrameOpen() throws Exception { - assertThat(this.session.isOpen(), is(false)); + assertThat(this.session.isOpen()).isFalse(); this.session.handleFrame(SockJsFrame.openFrame().getContent()); - assertThat(this.session.isOpen(), is(true)); + assertThat(this.session.isOpen()).isTrue(); assertTrue(this.connectFuture.isDone()); - assertThat(this.connectFuture.get(), sameInstance(this.session)); + assertThat(this.connectFuture.get()).isSameAs(this.session); verify(this.handler).afterConnectionEstablished(this.session); verifyNoMoreInteractions(this.handler); } @@ -88,16 +85,16 @@ public class ClientSockJsSessionTests { @Test public void handleFrameOpenWhenStatusNotNew() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); - assertThat(this.session.isOpen(), is(true)); + assertThat(this.session.isOpen()).isTrue(); this.session.handleFrame(SockJsFrame.openFrame().getContent()); - assertThat(this.session.disconnectStatus, equalTo(new CloseStatus(1006, "Server lost session"))); + assertThat(this.session.disconnectStatus).isEqualTo(new CloseStatus(1006, "Server lost session")); } @Test public void handleFrameOpenWithWebSocketHandlerException() throws Exception { willThrow(new IllegalStateException("Fake error")).given(this.handler).afterConnectionEstablished(this.session); this.session.handleFrame(SockJsFrame.openFrame().getContent()); - assertThat(this.session.isOpen(), is(true)); + assertThat(this.session.isOpen()).isTrue(); } @Test @@ -123,8 +120,8 @@ public class ClientSockJsSessionTests { public void handleFrameMessageWithBadData() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.handleFrame("a['bad data"); - assertThat(this.session.isOpen(), equalTo(false)); - assertThat(this.session.disconnectStatus, equalTo(CloseStatus.BAD_DATA)); + assertThat(this.session.isOpen()).isEqualTo(false); + assertThat(this.session.disconnectStatus).isEqualTo(CloseStatus.BAD_DATA); verify(this.handler).afterConnectionEstablished(this.session); verifyNoMoreInteractions(this.handler); } @@ -137,7 +134,7 @@ public class ClientSockJsSessionTests { willThrow(new IllegalStateException("Fake error")).given(this.handler) .handleMessage(this.session, new TextMessage("bar")); this.session.handleFrame(SockJsFrame.messageFrame(CODEC, "foo", "bar").getContent()); - assertThat(this.session.isOpen(), equalTo(true)); + assertThat(this.session.isOpen()).isEqualTo(true); verify(this.handler).afterConnectionEstablished(this.session); verify(this.handler).handleMessage(this.session, new TextMessage("foo")); verify(this.handler).handleMessage(this.session, new TextMessage("bar")); @@ -148,8 +145,8 @@ public class ClientSockJsSessionTests { public void handleFrameClose() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.handleFrame(SockJsFrame.closeFrame(1007, "").getContent()); - assertThat(this.session.isOpen(), equalTo(false)); - assertThat(this.session.disconnectStatus, equalTo(new CloseStatus(1007, ""))); + assertThat(this.session.isOpen()).isEqualTo(false); + assertThat(this.session.disconnectStatus).isEqualTo(new CloseStatus(1007, "")); verify(this.handler).afterConnectionEstablished(this.session); verifyNoMoreInteractions(this.handler); } @@ -166,7 +163,7 @@ public class ClientSockJsSessionTests { public void afterTransportClosed() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.afterTransportClosed(CloseStatus.SERVER_ERROR); - assertThat(this.session.isOpen(), equalTo(false)); + assertThat(this.session.isOpen()).isEqualTo(false); verify(this.handler).afterConnectionEstablished(this.session); verify(this.handler).afterConnectionClosed(this.session, CloseStatus.SERVER_ERROR); verifyNoMoreInteractions(this.handler); @@ -176,8 +173,8 @@ public class ClientSockJsSessionTests { public void close() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.close(); - assertThat(this.session.isOpen(), equalTo(false)); - assertThat(this.session.disconnectStatus, equalTo(CloseStatus.NORMAL)); + assertThat(this.session.isOpen()).isEqualTo(false); + assertThat(this.session.disconnectStatus).isEqualTo(CloseStatus.NORMAL); verify(this.handler).afterConnectionEstablished(this.session); verifyNoMoreInteractions(this.handler); } @@ -186,7 +183,7 @@ public class ClientSockJsSessionTests { public void closeWithStatus() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.close(new CloseStatus(3000, "reason")); - assertThat(this.session.disconnectStatus, equalTo(new CloseStatus(3000, "reason"))); + assertThat(this.session.disconnectStatus).isEqualTo(new CloseStatus(3000, "reason")); } @Test @@ -208,14 +205,14 @@ public class ClientSockJsSessionTests { @Test public void timeoutTask() { this.session.getTimeoutTask().run(); - assertThat(this.session.disconnectStatus, equalTo(new CloseStatus(2007, "Transport timed out"))); + assertThat(this.session.disconnectStatus).isEqualTo(new CloseStatus(2007, "Transport timed out")); } @Test public void send() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.sendMessage(new TextMessage("foo")); - assertThat(this.session.sentMessage, equalTo(new TextMessage("[\"foo\"]"))); + assertThat(this.session.sentMessage).isEqualTo(new TextMessage("[\"foo\"]")); } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java index 3a00442e70..1c837327aa 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java @@ -22,9 +22,7 @@ import org.junit.Test; import org.springframework.web.socket.sockjs.transport.TransportType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -62,7 +60,7 @@ public class SockJsUrlInfoTests { private void testInfoUrl(String scheme, String expectedScheme) throws Exception { SockJsUrlInfo info = new SockJsUrlInfo(new URI(scheme + "://example.com")); - assertThat(info.getInfoUrl(), is(equalTo(new URI(expectedScheme + "://example.com/info")))); + assertThat(info.getInfoUrl()).isEqualTo(new URI(expectedScheme + "://example.com/info")); } @Test @@ -83,7 +81,7 @@ public class SockJsUrlInfoTests { String sessionId = info.getSessionId(); String transport = transportType.toString().toLowerCase(); URI expected = new URI(expectedScheme + "://example.com/" + serverId + "/" + sessionId + "/" + transport); - assertThat(info.getTransportUrl(transportType), equalTo(expected)); + assertThat(info.getTransportUrl(transportType)).isEqualTo(expected); } } diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml index 85e16b0e3b..ff4a7efaee 100644 --- a/src/checkstyle/checkstyle-suppressions.xml +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -64,6 +64,12 @@ + + + + + + diff --git a/src/checkstyle/checkstyle.xml b/src/checkstyle/checkstyle.xml index abf129f3ca..11d3716d34 100644 --- a/src/checkstyle/checkstyle.xml +++ b/src/checkstyle/checkstyle.xml @@ -95,10 +95,17 @@ + + + + + + diff --git a/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java index 09adc2383e..7da0755a44 100644 --- a/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java +++ b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java @@ -27,8 +27,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Costin Leau @@ -55,24 +55,24 @@ public class ComponentBeanDefinitionParserTests { @Test public void testBionicBasic() throws Exception { Component cp = getBionicFamily(); - assertThat("Bionic-1", equalTo(cp.getName())); + assertThat("Bionic-1").isEqualTo(cp.getName()); } @Test public void testBionicFirstLevelChildren() throws Exception { Component cp = getBionicFamily(); List components = cp.getComponents(); - assertThat(2, equalTo(components.size())); - assertThat("Mother-1", equalTo(components.get(0).getName())); - assertThat("Rock-1", equalTo(components.get(1).getName())); + assertThat(2).isEqualTo(components.size()); + assertThat("Mother-1").isEqualTo(components.get(0).getName()); + assertThat("Rock-1").isEqualTo(components.get(1).getName()); } @Test public void testBionicSecondLevelChildren() throws Exception { Component cp = getBionicFamily(); List components = cp.getComponents().get(0).getComponents(); - assertThat(2, equalTo(components.size())); - assertThat("Karate-1", equalTo(components.get(0).getName())); - assertThat("Sport-1", equalTo(components.get(1).getName())); + assertThat(2).isEqualTo(components.size()); + assertThat("Karate-1").isEqualTo(components.get(0).getName()); + assertThat("Sport-1").isEqualTo(components.get(1).getName()); } } diff --git a/src/test/java/org/springframework/cache/annotation/EnableCachingIntegrationTests.java b/src/test/java/org/springframework/cache/annotation/EnableCachingIntegrationTests.java index a4ef28683e..2b4b5751ec 100644 --- a/src/test/java/org/springframework/cache/annotation/EnableCachingIntegrationTests.java +++ b/src/test/java/org/springframework/cache/annotation/EnableCachingIntegrationTests.java @@ -33,8 +33,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Repository; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -53,7 +52,7 @@ public class EnableCachingIntegrationTests { ctx.refresh(); assertCacheProxying(ctx); - assertThat(AopUtils.isCglibProxy(ctx.getBean(FooRepository.class)), is(true)); + assertThat(AopUtils.isCglibProxy(ctx.getBean(FooRepository.class))).isTrue(); } @Test diff --git a/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java b/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java index 82f3f67808..2bd659fa9f 100644 --- a/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java +++ b/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java @@ -57,12 +57,8 @@ import org.springframework.web.context.support.StandardServletEnvironment; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.context.support.XmlWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.notNullValue; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.context.ConfigurableApplicationContext.ENVIRONMENT_BEAN_NAME; import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.DERIVED_DEV_BEAN_NAME; @@ -137,8 +133,8 @@ public class EnvironmentSystemIntegrationTests { ctx.setEnvironment(prodEnv); new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(XML_PATH); ctx.refresh(); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -147,8 +143,8 @@ public class EnvironmentSystemIntegrationTests { ctx.setEnvironment(prodEnv); new AnnotatedBeanDefinitionReader(ctx).register(Config.class); ctx.refresh(); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -159,8 +155,8 @@ public class EnvironmentSystemIntegrationTests { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx); scanner.scan("org.springframework.core.env.scan1"); ctx.refresh(); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -170,9 +166,9 @@ public class EnvironmentSystemIntegrationTests { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx); scanner.scan("org.springframework.core.env.scan2"); ctx.refresh(); - assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment())); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(scanner.getEnvironment()).isEqualTo((Environment)ctx.getEnvironment()); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -186,8 +182,8 @@ public class EnvironmentSystemIntegrationTests { assertHasEnvironment(ctx, prodEnv); assertEnvironmentBeanRegistered(ctx); assertEnvironmentAwareInvoked(ctx, prodEnv); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -199,8 +195,8 @@ public class EnvironmentSystemIntegrationTests { assertEnvironmentBeanRegistered(ctx); assertHasEnvironment(ctx, prodEnv); assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment()); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -217,8 +213,8 @@ public class EnvironmentSystemIntegrationTests { assertEnvironmentBeanRegistered(ctx); assertHasEnvironment(ctx, prodEnv); assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment()); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -244,7 +240,7 @@ public class EnvironmentSystemIntegrationTests { ctx.register(ProdConfig.class); ctx.refresh(); - assertThat("should have prod bean", ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -257,8 +253,8 @@ public class EnvironmentSystemIntegrationTests { ctx.register(DevConfig.class); ctx.refresh(); - assertThat("should not have dev bean", ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat("should not have transitive bean", ctx.containsBean(TRANSITIVE_BEAN_NAME), is(false)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isFalse(); } @Test @@ -271,8 +267,8 @@ public class EnvironmentSystemIntegrationTests { ctx.register(DevConfig.class); ctx.refresh(); - assertThat("should have dev bean", ctx.containsBean(DEV_BEAN_NAME), is(true)); - assertThat("should have transitive bean", ctx.containsBean(TRANSITIVE_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isTrue(); + assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isTrue(); } @Test @@ -286,9 +282,9 @@ public class EnvironmentSystemIntegrationTests { ctx.refresh(); assertEnvironmentAwareInvoked(ctx, prodEnv); - assertThat("should have prod bean", ctx.containsBean(PROD_BEAN_NAME), is(true)); - assertThat("should not have dev bean", ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat("should not have transitive bean", ctx.containsBean(TRANSITIVE_BEAN_NAME), is(false)); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isFalse(); } @Test @@ -300,9 +296,9 @@ public class EnvironmentSystemIntegrationTests { ctx.register(DerivedDevConfig.class); ctx.refresh(); - assertThat("should have dev bean", ctx.containsBean(DEV_BEAN_NAME), is(true)); - assertThat("should have derived dev bean", ctx.containsBean(DERIVED_DEV_BEAN_NAME), is(true)); - assertThat("should have transitive bean", ctx.containsBean(TRANSITIVE_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isTrue(); + assertThat(ctx.containsBean(DERIVED_DEV_BEAN_NAME)).isTrue(); + assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isTrue(); } @Test @@ -312,9 +308,9 @@ public class EnvironmentSystemIntegrationTests { ctx.register(DerivedDevConfig.class); ctx.refresh(); - assertThat("should not have dev bean", ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat("should not have derived dev bean", ctx.containsBean(DERIVED_DEV_BEAN_NAME), is(false)); - assertThat("should not have transitive bean", ctx.containsBean(TRANSITIVE_BEAN_NAME), is(false)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(DERIVED_DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isFalse(); } @Test @@ -344,8 +340,7 @@ public class EnvironmentSystemIntegrationTests { ctx.setEnvironment(environment); ctx.register(ProfileExpressionConfig.class); ctx.refresh(); - assertThat("wrong presence of expression bean", - ctx.containsBean("expressionBean"), is(expected)); + assertThat(ctx.containsBean("expressionBean")).isEqualTo(expected); } @Test @@ -370,8 +365,8 @@ public class EnvironmentSystemIntegrationTests { assertHasEnvironment(ctx, prodWebEnv); assertEnvironmentBeanRegistered(ctx); assertEnvironmentAwareInvoked(ctx, prodWebEnv); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse(); + assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue(); } @Test @@ -434,23 +429,23 @@ public class EnvironmentSystemIntegrationTests { ctx.refresh(); ConfigurableEnvironment environment = ctx.getEnvironment(); - assertThat(environment, instanceOf(StandardServletEnvironment.class)); + assertThat(environment).isInstanceOf(StandardServletEnvironment.class); MutablePropertySources propertySources = environment.getPropertySources(); - assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); - assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME), is(true)); + assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)).isTrue(); + assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)).isTrue(); // ServletConfig gets precedence - assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); - assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), - lessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)))); + assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue"); + assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME))) + .isLessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME))); // but all params are available - assertThat(environment.getProperty("pContext1"), is("pContext1Value")); - assertThat(environment.getProperty("pConfig1"), is("pConfig1Value")); + assertThat(environment.getProperty("pContext1")).isEqualTo("pContext1Value"); + assertThat(environment.getProperty("pConfig1")).isEqualTo("pConfig1Value"); // Servlet* PropertySources have precedence over System* PropertySources - assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), - lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); + assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME))) + .isLessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); // Replace system properties with a mock property source for convenience MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); @@ -459,8 +454,8 @@ public class EnvironmentSystemIntegrationTests { propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties); // assert that servletconfig params resolve with higher precedence than sysprops - assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); - assertThat(environment.getProperty("pSysProps1"), is("pSysProps1Value")); + assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue"); + assertThat(environment.getProperty("pSysProps1")).isEqualTo("pSysProps1Value"); } @Test @@ -474,17 +469,17 @@ public class EnvironmentSystemIntegrationTests { ctx.refresh(); ConfigurableEnvironment environment = ctx.getEnvironment(); - assertThat(environment, instanceOf(StandardServletEnvironment.class)); + assertThat(environment).isInstanceOf(StandardServletEnvironment.class); MutablePropertySources propertySources = environment.getPropertySources(); - assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); + assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)).isTrue(); // ServletContext params are available - assertThat(environment.getProperty("pCommon"), is("pCommonContextValue")); - assertThat(environment.getProperty("pContext1"), is("pContext1Value")); + assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonContextValue"); + assertThat(environment.getProperty("pContext1")).isEqualTo("pContext1Value"); // Servlet* PropertySources have precedence over System* PropertySources - assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), - lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); + assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME))) + .isLessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); // Replace system properties with a mock property source for convenience MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); @@ -493,8 +488,8 @@ public class EnvironmentSystemIntegrationTests { propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties); // assert that servletcontext init params resolve with higher precedence than sysprops - assertThat(environment.getProperty("pCommon"), is("pCommonContextValue")); - assertThat(environment.getProperty("pSysProps1"), is("pSysProps1Value")); + assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonContextValue"); + assertThat(environment.getProperty("pSysProps1")).isEqualTo("pSysProps1Value"); } @Test @@ -513,21 +508,21 @@ public class EnvironmentSystemIntegrationTests { ConfigurableEnvironment environment = ctx.getEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); - assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); - assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME), is(true)); + assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)).isTrue(); + assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)).isTrue(); // ServletConfig gets precedence - assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); - assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), - lessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)))); + assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue"); + assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME))) + .isLessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME))); // but all params are available - assertThat(environment.getProperty("pContext1"), is("pContext1Value")); - assertThat(environment.getProperty("pConfig1"), is("pConfig1Value")); + assertThat(environment.getProperty("pContext1")).isEqualTo("pContext1Value"); + assertThat(environment.getProperty("pConfig1")).isEqualTo("pConfig1Value"); // Servlet* PropertySources have precedence over System* PropertySources - assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), - lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); + assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME))) + .isLessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); // Replace system properties with a mock property source for convenience MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); @@ -536,8 +531,8 @@ public class EnvironmentSystemIntegrationTests { propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties); // assert that servletconfig params resolve with higher precedence than sysprops - assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); - assertThat(environment.getProperty("pSysProps1"), is("pSysProps1Value")); + assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue"); + assertThat(environment.getProperty("pSysProps1")).isEqualTo("pSysProps1Value"); } @Test @@ -593,33 +588,33 @@ public class EnvironmentSystemIntegrationTests { private void assertEnvironmentBeanRegistered( ConfigurableApplicationContext ctx) { // ensure environment is registered as a bean - assertThat(ctx.containsBean(ENVIRONMENT_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(ENVIRONMENT_BEAN_NAME)).isTrue(); } private void assertHasStandardEnvironment(ApplicationContext ctx) { Environment defaultEnv = ctx.getEnvironment(); - assertThat(defaultEnv, notNullValue()); - assertThat(defaultEnv, instanceOf(StandardEnvironment.class)); + assertThat(defaultEnv).isNotNull(); + assertThat(defaultEnv).isInstanceOf(StandardEnvironment.class); } private void assertHasStandardServletEnvironment(WebApplicationContext ctx) { // ensure a default servlet environment exists Environment defaultEnv = ctx.getEnvironment(); - assertThat(defaultEnv, notNullValue()); - assertThat(defaultEnv, instanceOf(StandardServletEnvironment.class)); + assertThat(defaultEnv).isNotNull(); + assertThat(defaultEnv).isInstanceOf(StandardServletEnvironment.class); } private void assertHasEnvironment(ApplicationContext ctx, Environment expectedEnv) { // ensure the custom environment took Environment actualEnv = ctx.getEnvironment(); - assertThat(actualEnv, notNullValue()); - assertThat(actualEnv, is(expectedEnv)); + assertThat(actualEnv).isNotNull(); + assertThat(actualEnv).isEqualTo(expectedEnv); // ensure environment is registered as a bean - assertThat(ctx.containsBean(ENVIRONMENT_BEAN_NAME), is(true)); + assertThat(ctx.containsBean(ENVIRONMENT_BEAN_NAME)).isTrue(); } private void assertEnvironmentAwareInvoked(ConfigurableApplicationContext ctx, Environment expectedEnv) { - assertThat(ctx.getBean(EnvironmentAwareBean.class).environment, is(expectedEnv)); + assertThat(ctx.getBean(EnvironmentAwareBean.class).environment).isEqualTo(expectedEnv); } diff --git a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java index b382a4bb62..e6b75cee1c 100644 --- a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java +++ b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java @@ -41,10 +41,6 @@ import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @@ -85,9 +81,9 @@ public class ScheduledAndTransactionalAnnotationIntegrationTests { MyRepository repository = ctx.getBean(MyRepository.class); CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class); - assertThat("repository is not a proxy", AopUtils.isCglibProxy(repository), equalTo(true)); - assertThat("@Scheduled method never called", repository.getInvocationCount(), greaterThan(0)); - assertThat("no transactions were committed", txManager.commits, greaterThan(0)); + assertThat(AopUtils.isCglibProxy(repository)).isEqualTo(true); + assertThat(repository.getInvocationCount()).isGreaterThan(0); + assertThat(txManager.commits).isGreaterThan(0); } @Test @@ -100,9 +96,9 @@ public class ScheduledAndTransactionalAnnotationIntegrationTests { MyRepositoryWithScheduledMethod repository = ctx.getBean(MyRepositoryWithScheduledMethod.class); CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class); - assertThat("repository is not a proxy", AopUtils.isJdkDynamicProxy(repository), is(true)); - assertThat("@Scheduled method never called", repository.getInvocationCount(), greaterThan(0)); - assertThat("no transactions were committed", txManager.commits, greaterThan(0)); + assertThat(AopUtils.isJdkDynamicProxy(repository)).isTrue(); + assertThat(repository.getInvocationCount()).isGreaterThan(0); + assertThat(txManager.commits).isGreaterThan(0); } @Test @@ -114,8 +110,8 @@ public class ScheduledAndTransactionalAnnotationIntegrationTests { Thread.sleep(100); // allow @Scheduled method to be called several times MyRepositoryWithScheduledMethod repository = ctx.getBean(MyRepositoryWithScheduledMethod.class); - assertThat("repository is not a proxy", AopUtils.isCglibProxy(repository), is(true)); - assertThat("@Scheduled method never called", repository.getInvocationCount(), greaterThan(0)); + assertThat(AopUtils.isCglibProxy(repository)).isTrue(); + assertThat(repository.getInvocationCount()).isGreaterThan(0); } diff --git a/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java b/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java index c1098c5011..909eb3d491 100644 --- a/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java +++ b/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java @@ -44,9 +44,6 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; /** @@ -97,7 +94,7 @@ public class EnableTransactionManagementIntegrationTests { ctx.refresh(); assertTxProxying(ctx); - assertThat(AopUtils.isCglibProxy(ctx.getBean(FooRepository.class)), is(true)); + assertThat(AopUtils.isCglibProxy(ctx.getBean(FooRepository.class))).isTrue(); } @Test @@ -125,9 +122,9 @@ public class EnableTransactionManagementIntegrationTests { fooRepository.findAll(); CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class); - assertThat(txManager.begun, equalTo(1)); - assertThat(txManager.commits, equalTo(1)); - assertThat(txManager.rollbacks, equalTo(0)); + assertThat(txManager.begun).isEqualTo(1); + assertThat(txManager.commits).isEqualTo(1); + assertThat(txManager.rollbacks).isEqualTo(0); } @Test @@ -140,14 +137,14 @@ public class EnableTransactionManagementIntegrationTests { fooRepository.findAll(); CallCountingTransactionManager txManager1 = ctx.getBean("txManager1", CallCountingTransactionManager.class); - assertThat(txManager1.begun, equalTo(1)); - assertThat(txManager1.commits, equalTo(1)); - assertThat(txManager1.rollbacks, equalTo(0)); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.commits).isEqualTo(1); + assertThat(txManager1.rollbacks).isEqualTo(0); CallCountingTransactionManager txManager2 = ctx.getBean("txManager2", CallCountingTransactionManager.class); - assertThat(txManager2.begun, equalTo(0)); - assertThat(txManager2.commits, equalTo(0)); - assertThat(txManager2.rollbacks, equalTo(0)); + assertThat(txManager2.begun).isEqualTo(0); + assertThat(txManager2.commits).isEqualTo(0); + assertThat(txManager2.rollbacks).isEqualTo(0); } @Test diff --git a/src/test/java/org/springframework/transaction/annotation/ProxyAnnotationDiscoveryTests.java b/src/test/java/org/springframework/transaction/annotation/ProxyAnnotationDiscoveryTests.java index 5b7b18f70a..0cef8eb64d 100644 --- a/src/test/java/org/springframework/transaction/annotation/ProxyAnnotationDiscoveryTests.java +++ b/src/test/java/org/springframework/transaction/annotation/ProxyAnnotationDiscoveryTests.java @@ -22,9 +22,7 @@ import org.springframework.aop.support.AopUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; /** @@ -47,7 +45,7 @@ public class ProxyAnnotationDiscoveryTests { ctx.refresh(); AnnotatedServiceWithoutInterface s = ctx.getBean(AnnotatedServiceWithoutInterface.class); assertTrue("expected a subclass proxy", AopUtils.isCglibProxy(s)); - assertThat(s, instanceOf(AnnotatedServiceWithoutInterface.class)); + assertThat(s).isInstanceOf(AnnotatedServiceWithoutInterface.class); } @Test @@ -57,7 +55,7 @@ public class ProxyAnnotationDiscoveryTests { ctx.refresh(); AnnotatedServiceWithoutInterface s = ctx.getBean(AnnotatedServiceWithoutInterface.class); assertTrue("expected a subclass proxy", AopUtils.isCglibProxy(s)); - assertThat(s, instanceOf(AnnotatedServiceWithoutInterface.class)); + assertThat(s).isInstanceOf(AnnotatedServiceWithoutInterface.class); } @Test @@ -67,7 +65,7 @@ public class ProxyAnnotationDiscoveryTests { ctx.refresh(); NonAnnotatedService s = ctx.getBean(NonAnnotatedService.class); assertTrue("expected a subclass proxy", AopUtils.isCglibProxy(s)); - assertThat(s, instanceOf(AnnotatedServiceImpl.class)); + assertThat(s).isInstanceOf(AnnotatedServiceImpl.class); } @Test @@ -77,7 +75,7 @@ public class ProxyAnnotationDiscoveryTests { ctx.refresh(); NonAnnotatedService s = ctx.getBean(NonAnnotatedService.class); assertTrue("expected a jdk proxy", AopUtils.isJdkDynamicProxy(s)); - assertThat(s, not(instanceOf(AnnotatedServiceImpl.class))); + assertThat(s).isNotInstanceOf(AnnotatedServiceImpl.class); } @Test @@ -87,7 +85,7 @@ public class ProxyAnnotationDiscoveryTests { ctx.refresh(); AnnotatedService s = ctx.getBean(AnnotatedService.class); assertTrue("expected a subclass proxy", AopUtils.isCglibProxy(s)); - assertThat(s, instanceOf(NonAnnotatedServiceImpl.class)); + assertThat(s).isInstanceOf(NonAnnotatedServiceImpl.class); } @Test @@ -97,7 +95,7 @@ public class ProxyAnnotationDiscoveryTests { ctx.refresh(); AnnotatedService s = ctx.getBean(AnnotatedService.class); assertTrue("expected a jdk proxy", AopUtils.isJdkDynamicProxy(s)); - assertThat(s, not(instanceOf(NonAnnotatedServiceImpl.class))); + assertThat(s).isNotInstanceOf(NonAnnotatedServiceImpl.class); } }