From 02850f357f29f3dabe64750a3ab9405a94501b3a Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 20 May 2019 10:34:51 -0700 Subject: [PATCH] Migrate exception checking tests to use AssertJ Migrate tests that use `@Test(expectedException=...)` or `try...fail...catch` to use AssertJ's `assertThatException` instead. --- ...ctJAdviceParameterNameDiscovererTests.java | 24 +- .../AspectJExpressionPointcutTests.java | 56 +-- ...hodInvocationProceedingJoinPointTests.java | 38 +- .../TrickyAspectJPointcutExpressionTests.java | 11 +- .../aspectj/TypePatternClassFilterTests.java | 17 +- .../AbstractAspectJAdvisorFactoryTests.java | 98 ++-- .../annotation/ArgumentBindingTests.java | 12 +- .../AspectJPointcutAdvisorTests.java | 11 +- .../annotation/AspectMetadataTests.java | 6 +- .../annotation/AspectProxyFactoryTests.java | 16 +- ...AopNamespaceHandlerPointcutErrorTests.java | 31 +- .../aop/framework/AopProxyUtilsTests.java | 6 +- .../aop/framework/ProxyFactoryTests.java | 12 +- .../adapter/ThrowsAdviceInterceptorTests.java | 48 +- .../CustomizableTraceInterceptorTests.java | 50 +- .../interceptor/DebugInterceptorTests.java | 10 +- ...monPerformanceMonitorInterceptorTests.java | 10 +- .../PerformanceMonitorInterceptorTests.java | 10 +- .../SimpleTraceInterceptorTests.java | 11 +- .../aop/scope/DefaultScopedObjectTests.java | 21 +- ...elegatingIntroductionInterceptorTests.java | 6 +- .../target/HotSwappableTargetSourceTests.java | 17 +- .../target/ThreadLocalTargetSourceTests.java | 8 +- .../AnnotationAsyncExecutionAspectTests.java | 15 +- .../aspectj/JtaTransactionAspectsTests.java | 23 +- .../aspectj/TransactionAspectTests.java | 66 +-- .../beans/AbstractPropertyAccessorTests.java | 302 ++++-------- .../springframework/beans/BeanUtilsTests.java | 27 +- .../beans/BeanWrapperAutoGrowingTests.java | 24 +- .../beans/BeanWrapperGenericsTests.java | 12 +- .../beans/BeanWrapperTests.java | 62 +-- .../beans/ConcurrentBeanWrapperTests.java | 3 +- .../beans/ExtendedBeanInfoTests.java | 7 +- .../beans/MutablePropertyValuesTests.java | 11 +- .../factory/ConcurrentBeanFactoryTests.java | 3 +- .../DefaultListableBeanFactoryTests.java | 452 ++++++------------ .../beans/factory/Spr5475Tests.java | 15 +- ...AnnotationBeanWiringInfoResolverTests.java | 10 +- ...wiredAnnotationBeanPostProcessorTests.java | 186 +++---- ...njectAnnotationBeanPostProcessorTests.java | 12 +- .../annotation/LookupAnnotationTests.java | 10 +- ...uiredAnnotationBeanPostProcessorTests.java | 135 +++--- .../config/CustomScopeConfigurerTests.java | 17 +- .../MethodInvokingFactoryBeanTests.java | 90 +--- ...ObjectFactoryCreatingFactoryBeanTests.java | 34 +- .../PropertyResourceConfigurerTests.java | 38 +- .../ServiceLocatorFactoryBeanTests.java | 95 ++-- .../config/YamlMapFactoryBeanTests.java | 15 +- .../YamlPropertiesFactoryBeanTests.java | 10 +- .../ConstructorArgumentEntryTests.java | 9 +- .../parsing/FailFastProblemReporterTests.java | 8 +- .../factory/parsing/PropertyEntryTests.java | 19 +- .../support/BeanFactoryGenericsTests.java | 32 +- .../factory/support/LookupMethodTests.java | 10 +- .../factory/support/ManagedListTests.java | 12 +- .../factory/support/ManagedMapTests.java | 12 +- .../support/ManagedPropertiesTests.java | 12 +- .../factory/support/ManagedSetTests.java | 12 +- .../security/CallbacksSecurityTests.java | 144 ++---- .../wiring/BeanConfigurerSupportTests.java | 6 +- .../factory/wiring/BeanWiringInfoTests.java | 26 +- .../ClassNameBeanWiringInfoResolverTests.java | 6 +- .../factory/xml/AbstractBeanFactoryTests.java | 89 ++-- .../xml/DelegatingEntityResolverTests.java | 19 +- .../factory/xml/DuplicateBeanIdTests.java | 11 +- .../beans/factory/xml/FactoryMethodTests.java | 51 +- .../xml/ProfileXmlBeanDefinitionTests.java | 6 +- .../factory/xml/SchemaValidationTests.java | 23 +- ...impleConstructorNamespaceHandlerTests.java | 8 +- .../SimplePropertyNamespaceHandlerTests.java | 8 +- .../factory/xml/XmlBeanCollectionTests.java | 14 +- .../xml/XmlBeanDefinitionReaderTests.java | 11 +- .../DefaultNamespaceHandlerResolverTests.java | 15 +- .../CustomCollectionEditorTests.java | 16 +- .../propertyeditors/CustomEditorTests.java | 92 ++-- .../propertyeditors/FileEditorTests.java | 6 +- .../InputStreamEditorTests.java | 11 +- .../propertyeditors/PathEditorTests.java | 6 +- .../propertyeditors/ReaderEditorTests.java | 11 +- .../ResourceBundleEditorTests.java | 21 +- .../beans/propertyeditors/URLEditorTests.java | 11 +- .../cache/ehcache/EhCacheSupportTests.java | 17 +- .../config/AbstractJCacheAnnotationTests.java | 181 ++----- .../config/JCacheCustomInterceptorTests.java | 17 +- .../mail/SimpleMailMessageTests.java | 11 +- .../javamail/InternetAddressEditorTests.java | 6 +- .../mail/javamail/JavaMailSenderTests.java | 32 +- .../scheduling/quartz/QuartzSupportTests.java | 6 +- .../BeanValidationPostProcessorTests.java | 26 +- .../MethodValidationTests.java | 59 +-- .../ValidatorFactoryTests.java | 18 +- .../AfterThrowingAdviceBindingTests.java | 31 +- .../AspectAndAdvicePrecedenceTests.java | 6 +- .../aop/aspectj/DeclareParentsTests.java | 11 +- .../autoproxy/spr3064/SPR3064Tests.java | 14 +- .../AopNamespaceHandlerAdviceTypeTests.java | 13 +- .../AopNamespaceHandlerArgNamesTests.java | 13 +- .../AopNamespaceHandlerReturningTests.java | 13 +- .../AopNamespaceHandlerThrowingTests.java | 13 +- .../MethodLocatingFactoryBeanTests.java | 31 +- .../aop/framework/AbstractAopProxyTests.java | 237 +++------ .../aop/framework/CglibProxyTests.java | 12 +- .../aop/framework/JdkDynamicProxyTests.java | 6 +- .../aop/framework/ProxyFactoryBeanTests.java | 154 ++---- .../AdvisorAdapterRegistrationTests.java | 24 +- .../BeanNameAutoProxyCreatorInitTests.java | 6 +- .../BeanNameAutoProxyCreatorTests.java | 20 +- .../target/CommonsPool2TargetSourceTests.java | 20 +- .../InjectAnnotationAutowireContextTests.java | 135 ++---- ...alifierAnnotationAutowireContextTests.java | 137 +++--- .../factory/xml/QualifierAnnotationTests.java | 22 +- .../factory/xml/XmlBeanFactoryTests.java | 202 +++----- .../support/CustomNamespaceHandlerTests.java | 13 +- .../cache/CacheReproTests.java | 5 +- .../config/AbstractCacheAnnotationTests.java | 71 +-- .../cache/config/CacheAdviceParserTests.java | 12 +- .../cache/config/CustomInterceptorTests.java | 17 +- .../CacheResolverCustomizationTests.java | 26 +- .../interceptor/ExpressionEvaluatorTests.java | 13 +- .../AbstractApplicationContextTests.java | 7 +- ...notationConfigApplicationContextTests.java | 12 +- .../AnnotationScopeMetadataResolverTests.java | 11 +- .../ClassPathBeanDefinitionScannerTests.java | 48 +- ...ScanParserBeanDefinitionDefaultsTests.java | 11 +- ...nParserWithUserDefinedStrategiesTests.java | 22 +- .../ConfigurationClassPostProcessorTests.java | 86 ++-- .../ImportVersusDirectRegistrationTests.java | 19 +- ...alidConfigurationClassDefinitionTests.java | 15 +- ...wiredAnnotationBeanPostProcessorTests.java | 20 +- .../AnnotationDrivenEventListenerTests.java | 39 +- .../event/ApplicationContextEventTests.java | 13 +- .../EventPublicationInterceptorTests.java | 30 +- .../expression/FactoryBeanAccessTests.java | 36 +- .../groovy/GroovyApplicationContextTests.java | 6 +- .../ClassPathXmlApplicationContextTests.java | 51 +- .../ConversionServiceFactoryBeanTests.java | 6 +- .../GenericApplicationContextTests.java | 33 +- ...rtyResourceConfigurerIntegrationTests.java | 90 ++-- ...ertySourcesPlaceholderConfigurerTests.java | 11 +- .../ResourceBundleMessageSourceTests.java | 41 +- .../support/StaticMessageSourceTests.java | 5 +- .../LocalSlsbInvokerInterceptorTests.java | 23 +- ...StatelessSessionProxyFactoryBeanTests.java | 25 +- ...mpleRemoteSlsbInvokerInterceptorTests.java | 51 +- ...StatelessSessionProxyFactoryBeanTests.java | 46 +- .../number/CurrencyStyleFormatterTests.java | 11 +- .../number/NumberStyleFormatterTests.java | 11 +- .../number/PercentStyleFormatterTests.java | 11 +- ...tingConversionServiceFactoryBeanTests.java | 22 +- .../FormattingConversionServiceTests.java | 11 +- .../ReflectiveLoadTimeWeaverTests.java | 17 +- .../access/MBeanClientInterceptorTests.java | 29 +- .../export/MBeanExporterOperationsTests.java | 12 +- .../jmx/export/MBeanExporterTests.java | 22 +- .../jmx/export/NotificationListenerTests.java | 10 +- ...aceBasedMBeanInfoAssemblerMappedTests.java | 20 +- .../ModelMBeanNotificationPublisherTests.java | 21 +- .../ConnectorServerFactoryBeanTests.java | 10 +- ...MBeanServerConnectionFactoryBeanTests.java | 6 +- .../support/MBeanServerFactoryBeanTests.java | 25 +- .../jndi/JndiObjectFactoryBeanTests.java | 71 +-- .../jndi/JndiTemplateEditorTests.java | 11 +- .../jndi/JndiTemplateTests.java | 29 +- .../jndi/SimpleNamingContextTests.java | 53 +- .../remoting/rmi/RmiSupportTests.java | 108 +---- ...AsyncAnnotationBeanPostProcessorTests.java | 26 +- .../annotation/AsyncExecutionTests.java | 82 +--- .../annotation/AsyncResultTests.java | 50 +- .../annotation/EnableAsyncTests.java | 45 +- ...duledAnnotationBeanPostProcessorTests.java | 26 +- .../AbstractSchedulingTaskExecutorTests.java | 47 +- .../ScheduledExecutorFactoryBeanTests.java | 16 +- .../ThreadPoolTaskSchedulerTests.java | 13 +- .../ExecutorBeanDefinitionParserTests.java | 11 +- .../support/CronSequenceGeneratorTests.java | 21 +- .../scheduling/support/CronTriggerTests.java | 66 ++- .../scripting/bsh/BshScriptFactoryTests.java | 44 +- .../groovy/GroovyAspectIntegrationTests.java | 43 +- .../scripting/groovy/GroovyAspectTests.java | 12 +- .../groovy/GroovyScriptFactoryTests.java | 93 ++-- .../RefreshableScriptTargetSourceTests.java | 6 +- .../ScriptFactoryPostProcessorTests.java | 22 +- .../support/StaticScriptSourceTests.java | 16 +- .../org/springframework/ui/ModelMapTests.java | 16 +- .../DataBinderFieldAccessTests.java | 103 ++-- .../validation/DataBinderTests.java | 234 ++++----- .../validation/ValidationUtilsTests.java | 11 +- .../BeanValidationPostProcessorTests.java | 26 +- .../beanvalidation/MethodValidationTests.java | 59 +-- .../beanvalidation/ValidatorFactoryTests.java | 18 +- .../core/CollectionFactoryTests.java | 118 +++-- .../springframework/core/ConstantsTests.java | 66 +-- .../core/MethodParameterTests.java | 6 +- .../SynthesizingMethodParameterTests.java | 6 +- .../core/codec/AbstractDecoderTestCase.java | 13 +- .../core/codec/ResourceDecoderTests.java | 9 +- .../core/convert/TypeDescriptorTests.java | 22 +- .../converter/ConvertingComparatorTests.java | 22 +- .../DefaultConversionServiceTests.java | 26 +- .../CollectionToCollectionConverterTests.java | 11 +- .../GenericConversionServiceTests.java | 98 ++-- .../support/MapToMapConverterTests.java | 11 +- .../core/env/MutablePropertySourcesTests.java | 52 +- .../core/env/ProfilesTests.java | 11 +- .../PropertySourcesPropertyResolverTests.java | 72 +-- .../env/SimpleCommandLineParserTests.java | 32 +- .../core/env/StandardEnvironmentTests.java | 92 ++-- .../core/io/ClassPathResourceTests.java | 17 +- .../core/io/ResourceEditorTests.java | 15 +- .../core/io/ResourceTests.java | 70 +-- .../core/io/buffer/DataBufferTests.java | 78 +-- .../core/io/buffer/DataBufferUtilsTests.java | 15 +- .../LeakAwareDataBufferFactoryTests.java | 9 +- .../core/io/buffer/PooledDataBufferTests.java | 6 +- ...hMatchingResourcePatternResolverTests.java | 6 +- .../ResourceArrayPropertyEditorTests.java | 8 +- .../core/io/support/ResourceRegionTests.java | 16 +- .../SerializationConverterTests.java | 31 +- .../util/CompositeIteratorTests.java | 65 +-- .../util/FastByteArrayOutputStreamTests.java | 12 +- .../springframework/util/MimeTypeTests.java | 92 ++-- .../util/NumberUtilsTests.java | 112 ++--- .../util/PropertyPlaceholderHelperTests.java | 6 +- .../util/ReflectionUtilsTests.java | 16 +- .../ResizableByteArrayOutputStreamTests.java | 6 +- .../util/SerializationUtilsTests.java | 19 +- .../util/StringUtilsTests.java | 11 +- .../util/SystemPropertyUtilsTests.java | 7 +- .../comparator/InvertibleComparatorTests.java | 11 +- .../concurrent/ListenableFutureTaskTests.java | 44 +- .../SettableListenableFutureTests.java | 72 +-- .../xml/ListBasedXMLEventReaderTests.java | 14 +- .../util/xml/SimpleNamespaceContextTests.java | 32 +- .../util/xml/TransformerUtilsTests.java | 16 +- .../spel/AbstractExpressionTests.java | 108 ++--- .../spel/ArrayConstructorTests.java | 3 +- .../spel/ConstructorInvocationTests.java | 44 +- .../expression/spel/EvaluationTests.java | 269 ++++------- .../spel/ExpressionLanguageScenarioTests.java | 30 +- .../expression/spel/ExpressionStateTests.java | 47 +- .../expression/spel/ListTests.java | 6 +- .../spel/LiteralExpressionTests.java | 64 +-- .../expression/spel/MapTests.java | 6 +- .../spel/MethodInvocationTests.java | 57 +-- .../expression/spel/ParsingTests.java | 21 +- .../expression/spel/PerformanceTests.java | 25 +- .../expression/spel/PropertyAccessTests.java | 77 +-- .../spel/ScenariosForSpringSecurity.java | 27 +- .../expression/spel/SetValueTests.java | 93 ++-- .../spel/SpelCompilationCoverageTests.java | 66 +-- .../spel/SpelCompilationPerformanceTests.java | 2 +- .../expression/spel/SpelExceptionTests.java | 26 +- .../expression/spel/SpelReproTests.java | 109 ++--- .../spel/StandardTypeLocatorTests.java | 14 +- .../spel/TemplateExpressionParsingTests.java | 118 ++--- .../spel/VariableAndFunctionTests.java | 18 +- .../expression/spel/ast/OpPlusTests.java | 12 +- .../spel/standard/SpelParserTests.java | 123 ++--- .../spel/support/ReflectionHelperTests.java | 110 ++--- .../spel/support/StandardComponentsTests.java | 6 +- .../InitializeDatabaseIntegrationTests.java | 6 +- .../jdbc/core/SingleColumnRowMapperTests.java | 7 +- .../BeanPropertySqlParameterSourceTests.java | 16 +- .../MapSqlParameterSourceTests.java | 6 +- .../namedparam/NamedParameterUtilsTests.java | 15 +- .../jdbc/core/support/SqlLobValueTests.java | 24 +- .../DataSourceJtaTransactionTests.java | 13 +- .../DataSourceTransactionManagerTests.java | 172 +++---- .../DriverManagerDataSourceTests.java | 13 +- .../EmbeddedDatabaseBuilderTests.java | 21 +- .../init/ResourceDatabasePopulatorTests.java | 31 +- .../BeanFactoryDataSourceLookupTests.java | 17 +- .../lookup/JndiDataSourceLookupTests.java | 6 +- .../SQLStateSQLExceptionTranslatorTests.java | 6 +- .../rowset/ResultSetWrappingRowSetTests.java | 14 +- .../JmsTransactionManagerTests.java | 11 +- .../jms/core/JmsTemplateTests.java | 14 +- .../SimpleMessageListenerContainerTests.java | 22 +- .../adapter/MessageListenerAdapterTests.java | 39 +- .../MessagingMessageListenerAdapterTests.java | 32 +- .../jms/support/JmsAccessorTests.java | 11 +- .../support/SimpleMessageConverterTests.java | 26 +- .../JmsDestinationAccessorTests.java | 17 +- .../JndiDestinationResolverTests.java | 16 +- .../messaging/MessageHeadersTests.java | 6 +- .../DefaultContentTypeResolverTests.java | 12 +- .../MappingJackson2MessageConverterTests.java | 6 +- .../MarshallingMessageConverterTests.java | 11 +- .../converter/MessageConverterTests.java | 6 +- .../core/CachingDestinationResolverTests.java | 11 +- ...nationResolvingMessagingTemplateTests.java | 6 +- .../core/MessageReceivingTemplateTests.java | 6 +- .../MessageRequestReplyTemplateTests.java | 6 +- .../core/MessageSendingTemplateTests.java | 12 +- ...onVariableMethodArgumentResolverTests.java | 6 +- .../HeaderMethodArgumentResolverTests.java | 6 +- .../HeadersMethodArgumentResolverTests.java | 6 +- ...onExceptionHandlerMethodResolverTests.java | 11 +- ...onVariableMethodArgumentResolverTests.java | 6 +- .../HeaderMethodArgumentResolverTests.java | 6 +- .../HeadersMethodArgumentResolverTests.java | 6 +- .../InvocableHandlerMethodTests.java | 120 ++--- .../invocation/MethodMessageHandlerTests.java | 6 +- .../reactive/InvocableHandlerMethodTests.java | 52 +- .../reactive/MethodMessageHandlerTests.java | 6 +- .../rsocket/DefaultRSocketRequesterTests.java | 12 +- .../SimpleBrokerMessageHandlerTests.java | 6 +- .../stomp/BufferingStompDecoderTests.java | 28 +- ...erRelayMessageHandlerIntegrationTests.java | 6 +- .../simp/stomp/StompClientSupportTests.java | 11 +- .../simp/stomp/StompDecoderTests.java | 16 +- .../support/MessageBuilderTests.java | 11 +- ...rEntityManagerFactoryIntegrationTests.java | 93 ++-- ...nManagedEntityManagerIntegrationTests.java | 11 +- ...rManagedEntityManagerIntegrationTests.java | 31 +- .../orm/jpa/DefaultJpaDialectTests.java | 12 +- .../jpa/EntityManagerFactoryUtilsTests.java | 11 +- .../orm/jpa/JpaTransactionManagerTests.java | 77 +-- ...ontainerEntityManagerFactoryBeanTests.java | 30 +- .../jpa/SharedEntityManagerCreatorTests.java | 51 +- ...iEntityManagerFactoryIntegrationTests.java | 9 +- ...rySpringBeanContainerIntegrationTests.java | 37 +- .../PersistenceXmlParsingTests.java | 18 +- .../support/PersistenceInjectionTests.java | 29 +- .../SharedEntityManagerFactoryTests.java | 11 +- .../oxm/jaxb/Jaxb2MarshallerTests.java | 22 +- .../oxm/jibx/JibxMarshallerTests.java | 6 +- .../mock/web/MockFilterChainTests.java | 54 +-- .../mock/web/MockHttpServletRequestTests.java | 16 +- .../web/MockHttpServletResponseTests.java | 6 +- .../mock/web/MockHttpSessionTests.java | 94 ++-- ...ntextManagerSuppressedExceptionsTests.java | 25 +- .../context/TestExecutionListenersTests.java | 6 +- .../context/cache/LruContextCacheTests.java | 11 +- ...ctionalAfterTestMethodSqlScriptsTests.java | 12 +- .../junit4/SpringJUnit4ClassRunnerTests.java | 6 +- .../orm/HibernateSessionFlushingTests.java | 26 +- .../support/ActiveProfilesUtilsTests.java | 12 +- ...notationConfigContextLoaderUtilsTests.java | 6 +- ...ntextLoaderUtilsContextHierarchyTests.java | 26 +- .../DelegatingSmartContextLoaderTests.java | 18 +- ...ansactionalTestExecutionListenerTests.java | 13 +- .../test/util/AopTestUtilsTests.java | 11 +- .../test/util/ReflectionTestUtilsTests.java | 30 +- .../client/MockRestServiceServerTests.java | 27 +- .../match/ContentRequestMatchersTests.java | 63 +-- .../match/JsonPathRequestMatchersTests.java | 71 +-- .../match/XpathRequestMatchersTests.java | 39 +- .../test/web/client/samples/SampleTests.java | 6 +- .../reactive/server/HeaderAssertionTests.java | 146 ++---- .../reactive/server/StatusAssertionTests.java | 93 ++-- .../web/servlet/DefaultMvcResultTests.java | 9 +- .../htmlunit/HtmlUnitRequestBuilderTests.java | 31 +- .../MockMvcConnectionBuilderSupportTests.java | 11 +- .../MockMvcWebClientBuilderTests.java | 11 +- .../htmlunit/MockMvcWebConnectionTests.java | 37 +- .../htmlunit/MockWebResponseBuilderTests.java | 11 +- .../MockMvcHtmlUnitDriverBuilderTests.java | 11 +- .../result/ContentResultMatchersTests.java | 39 +- .../FlashAttributeResultMatchersTests.java | 14 +- .../result/JsonPathResultMatchersTests.java | 87 ++-- .../result/MockMvcResultMatchersTests.java | 11 +- .../result/ModelResultMatchersTests.java | 61 ++- .../result/XpathResultMatchersTests.java | 39 +- .../resultmatchers/HeaderAssertionTests.java | 16 +- .../setup/StandaloneMockMvcBuilderTests.java | 21 +- ...tenceExceptionTranslationAdvisorTests.java | 67 +-- ...xceptionTranslationPostProcessorTests.java | 26 +- .../dao/support/DataAccessUtilsTests.java | 167 ++----- .../LocalConnectionFactoryBeanTests.java | 6 +- .../JtaTransactionManagerTests.java | 198 ++------ .../transaction/TransactionSupportTests.java | 183 +++---- .../transaction/TxNamespaceHandlerTests.java | 14 +- ...AnnotationTransactionInterceptorTests.java | 44 +- ...ationTransactionNamespaceHandlerTests.java | 16 +- .../EnableTransactionManagementTests.java | 16 +- .../TransactionalEventListenerTests.java | 51 +- ...bstractReactiveTransactionAspectTests.java | 2 +- .../AbstractTransactionAspectTests.java | 10 +- .../BeanFactoryTransactionTests.java | 16 +- .../interceptor/RollbackRuleTests.java | 16 +- .../TransactionAttributeEditorTests.java | 11 +- ...TransactionAttributeSourceEditorTests.java | 6 +- .../WebSphereUowTransactionManagerTests.java | 71 +-- .../support/SimpleTransactionScopeTests.java | 46 +- .../http/ContentDispositionTests.java | 26 +- .../http/HttpHeadersTests.java | 23 +- .../springframework/http/HttpRangeTests.java | 66 ++- .../springframework/http/MediaTypeTests.java | 67 ++- ...stractAsyncHttpRequestFactoryTestCase.java | 21 +- .../AbstractHttpRequestFactoryTestCase.java | 24 +- .../client/support/ProxyFactoryBeanTests.java | 16 +- .../codec/cbor/Jackson2CborDecoderTests.java | 13 +- .../codec/cbor/Jackson2CborEncoderTests.java | 6 +- .../codec/json/Jackson2JsonDecoderTests.java | 6 +- .../codec/json/Jackson2JsonEncoderTests.java | 6 +- .../DefaultMultipartMessageReaderTests.java | 5 +- .../codec/protobuf/ProtobufDecoderTests.java | 6 +- .../converter/HttpMessageConverterTests.java | 6 +- ...jectToStringHttpMessageConverterTests.java | 6 +- .../json/GsonHttpMessageConverterTests.java | 6 +- .../Jackson2ObjectMapperBuilderTests.java | 12 +- .../Jackson2ObjectMapperFactoryBeanTests.java | 6 +- .../json/JsonbHttpMessageConverterTests.java | 6 +- ...pingJackson2HttpMessageConverterTests.java | 18 +- .../MarshallingHttpMessageConverterTests.java | 39 +- .../ContextPathCompositeHandlerTests.java | 12 +- .../reactive/ServerHttpRequestTests.java | 6 +- .../httpinvoker/HttpInvokerTests.java | 89 +--- .../remoting/jaxws/JaxWsSupportTests.java | 32 +- ...entNegotiationManagerFactoryBeanTests.java | 11 +- ...HeaderContentNegotiationStrategyTests.java | 6 +- ...ensionContentNegotiationStrategyTests.java | 6 +- .../web/bind/ServletRequestUtilsTests.java | 173 ++----- .../AsyncRestTemplateIntegrationTests.java | 25 +- ...ltResponseErrorHandlerHttpStatusTests.java | 13 +- .../DefaultResponseErrorHandlerTests.java | 39 +- .../ExtractingResponseErrorHandlerTests.java | 37 +- .../client/RestTemplateIntegrationTests.java | 48 +- .../web/client/RestTemplateTests.java | 46 +- .../RequestAndSessionScopedBeanTests.java | 22 +- .../context/request/RequestScopeTests.java | 17 +- .../ServletRequestAttributesTests.java | 17 +- .../StandardServletAsyncWebRequestTests.java | 29 +- .../request/async/WebAsyncManagerTests.java | 72 +-- .../web/context/support/Spr8510Tests.java | 65 +-- .../web/cors/CorsConfigurationTests.java | 11 +- .../UrlBasedCorsConfigurationSourceTests.java | 6 +- .../filter/DelegatingFilterProxyTests.java | 6 +- .../filter/RelativeRedirectFilterTests.java | 11 +- .../web/filter/RequestContextFilterTests.java | 16 +- ...ookieValueMethodArgumentResolverTests.java | 8 +- .../ErrorsMethodArgumentResolverTests.java | 11 +- .../ExceptionHandlerMethodResolverTests.java | 11 +- .../InitBinderDataBinderFactoryTests.java | 6 +- .../ModelAttributeMethodProcessorTests.java | 6 +- .../method/annotation/ModelFactoryTests.java | 11 +- ...uestHeaderMethodArgumentResolverTests.java | 6 +- ...questParamMethodArgumentResolverTests.java | 26 +- .../WebArgumentResolverAdapterTests.java | 17 +- ...rMethodArgumentResolverCompositeTests.java | 6 +- ...ethodReturnValueHandlerCompositeTests.java | 6 +- .../support/InvocableHandlerMethodTests.java | 109 ++--- .../ByteArrayMultipartFileEditorTests.java | 6 +- .../HeaderWebSessionIdResolverTests.java | 8 +- .../session/InMemoryWebSessionStoreTests.java | 13 +- .../ContentCachingRequestWrapperTests.java | 12 +- .../web/util/TagUtilsTests.java | 47 +- .../web/util/UriComponentsBuilderTests.java | 6 +- .../web/util/UriComponentsTests.java | 17 +- .../web/util/UriTemplateTests.java | 11 +- .../web/util/UriUtilsTests.java | 6 +- .../util/pattern/PathPatternParserTests.java | 42 +- .../web/util/pattern/PathPatternTests.java | 11 +- .../HeaderContentTypeResolverTests.java | 8 +- .../ParameterContentTypeResolverTests.java | 8 +- .../function/BodyExtractorsTests.java | 10 +- .../client/DefaultClientResponseTests.java | 20 +- .../client/DefaultWebClientTests.java | 6 +- .../client/ExchangeFilterFunctionsTests.java | 6 +- .../server/DefaultServerRequestTests.java | 6 +- .../DefaultServerResponseBuilderTests.java | 6 +- .../resource/FixedVersionStrategyTests.java | 6 +- .../resource/ResourceWebHandlerTests.java | 12 +- .../CompositeRequestConditionTests.java | 11 +- .../RequestConditionHolderTests.java | 11 +- .../method/HandlerMethodMappingTests.java | 6 +- .../method/InvocableHandlerMethodTests.java | 57 +-- ...ookieValueMethodArgumentResolverTests.java | 14 +- ...ssionValueMethodArgumentResolverTests.java | 14 +- .../GlobalCorsConfigIntegrationTests.java | 37 +- ...HttpEntityMethodArgumentResolverTests.java | 14 +- .../InitBinderBindingContextTests.java | 6 +- ...xVariablesMethodArgumentResolverTests.java | 11 +- .../annotation/ModelInitializerTests.java | 12 +- ...ariableMapMethodArgumentResolverTests.java | 14 +- ...thVariableMethodArgumentResolverTests.java | 14 +- ...equestBodyMethodArgumentResolverTests.java | 6 +- ...tHeaderMapMethodArgumentResolverTests.java | 14 +- ...uestHeaderMethodArgumentResolverTests.java | 14 +- ...pingExceptionHandlingIntegrationTests.java | 36 +- ...stParamMapMethodArgumentResolverTests.java | 15 +- ...questParamMethodArgumentResolverTests.java | 29 +- ...ebExchangeMethodArgumentResolverTests.java | 14 +- .../view/HttpMessageWriterViewTests.java | 14 +- .../result/view/RedirectViewTests.java | 6 +- .../web/context/ContextLoaderTests.java | 94 ++-- .../XmlWebApplicationContextTests.java | 33 +- .../support/HttpRequestHandlerTests.java | 27 +- .../support/ServletContextSupportTests.java | 28 +- .../WebApplicationObjectSupportTests.java | 11 +- .../web/servlet/DispatcherServletTests.java | 71 +-- .../web/servlet/config/MvcNamespaceTests.java | 6 +- .../function/DefaultServerRequestTests.java | 12 +- .../function/RouterFunctionBuilderTests.java | 6 +- .../servlet/function/RouterFunctionTests.java | 6 +- .../BeanNameUrlHandlerMappingTests.java | 11 +- .../HandlerMappingIntrospectorTests.java | 6 +- .../handler/HandlerMethodMappingTests.java | 11 +- .../handler/SimpleUrlHandlerMappingTests.java | 15 +- .../i18n/CookieLocaleResolverTests.java | 26 +- .../web/servlet/i18n/LocaleResolverTests.java | 8 +- .../mvc/WebContentInterceptorTests.java | 6 +- .../CompositeRequestConditionTests.java | 11 +- .../ConsumesRequestConditionTests.java | 19 +- .../ProducesRequestConditionTests.java | 19 +- .../RequestConditionHolderTests.java | 11 +- ...RequestMappingInfoHandlerMappingTests.java | 87 ++-- ...equestAttributesArgumentResolverTests.java | 12 +- ...xVariablesMethodArgumentResolverTests.java | 11 +- ...ResolverMethodReturnValueHandlerTests.java | 11 +- .../MvcUriComponentsBuilderTests.java | 12 +- ...thVariableMethodArgumentResolverTests.java | 8 +- ...equestPartMethodArgumentResolverTests.java | 36 +- ...tResponseBodyMethodProcessorMockTests.java | 54 ++- ...questResponseBodyMethodProcessorTests.java | 15 +- .../annotation/ResponseBodyEmitterTests.java | 17 +- .../ServletInvocableHandlerMethodTests.java | 8 +- .../resource/FixedVersionStrategyTests.java | 6 +- .../ResourceHttpRequestHandlerTests.java | 12 +- .../web/servlet/tags/BindTagTests.java | 29 +- .../web/servlet/tags/ParamTagTests.java | 6 +- .../servlet/tags/form/CheckboxTagTests.java | 23 +- .../servlet/tags/form/CheckboxesTagTests.java | 23 +- .../web/servlet/tags/form/FormTagTests.java | 13 +- .../tags/form/HiddenInputTagTests.java | 12 +- .../web/servlet/tags/form/InputTagTests.java | 22 +- .../web/servlet/tags/form/OptionTagTests.java | 24 +- .../tags/form/PasswordInputTagTests.java | 12 +- .../tags/form/RadioButtonTagTests.java | 12 +- .../tags/form/RadioButtonsTagTests.java | 23 +- .../web/servlet/tags/form/SelectTagTests.java | 15 +- .../web/servlet/theme/ThemeResolverTests.java | 8 +- .../web/servlet/view/BaseViewTests.java | 43 +- .../view/InternalResourceViewTests.java | 6 +- .../web/servlet/view/RedirectViewTests.java | 6 +- .../view/RedirectViewUriTemplateTests.java | 6 +- .../view/ResourceBundleViewResolverTests.java | 25 +- .../web/servlet/view/ViewResolverTests.java | 41 +- .../freemarker/FreeMarkerConfigurerTests.java | 7 +- .../groovy/GroovyMarkupConfigurerTests.java | 9 +- .../view/groovy/GroovyMarkupViewTests.java | 12 +- .../view/xml/MappingJackson2XmlViewTests.java | 10 +- .../view/xml/MarshallingViewTests.java | 40 +- .../web/servlet/view/xslt/XsltViewTests.java | 11 +- .../StandardWebSocketClientTests.java | 6 +- ...essageBrokerBeanDefinitionParserTests.java | 20 +- .../BeanCreatingHandlerProviderTests.java | 6 +- ...currentWebSocketSessionDecoratorTests.java | 33 +- .../SubProtocolWebSocketHandlerTests.java | 16 +- .../messaging/WebSocketStompClientTests.java | 11 +- .../OriginHandshakeInterceptorTests.java | 6 +- .../sockjs/client/XhrTransportTests.java | 11 +- .../handler/DefaultSockJsServiceTests.java | 6 +- .../HttpReceivingTransportHandlerTests.java | 22 +- .../transport/session/SockJsSessionTests.java | 35 +- src/checkstyle/checkstyle-suppressions.xml | 5 + src/checkstyle/checkstyle.xml | 10 +- .../EnvironmentSystemIntegrationTests.java | 10 +- ...ansactionalAnnotationIntegrationTests.java | 14 +- ...TransactionManagementIntegrationTests.java | 33 +- 561 files changed, 6592 insertions(+), 10389 deletions(-) diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java index b30ff7c8674..3e95e6ed4f8 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java @@ -23,9 +23,9 @@ import org.junit.Test; import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer.AmbiguousBindingException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * Unit tests for the {@link AspectJAdviceParameterNameDiscoverer} class. @@ -226,8 +226,7 @@ public class AspectJAdviceParameterNameDiscovererTests { return candidate; } } - fail("Bad test specification, no method '" + name + "' found in test class"); - return null; + throw new AssertionError("Bad test specification, no method '" + name + "' found in test class"); } protected void assertParameterNames(Method method, String pointcut, String[] parameterNames) { @@ -262,27 +261,20 @@ public class AspectJAdviceParameterNameDiscovererTests { } } - protected void assertException(Method method, String pointcut, Class exceptionType, String message) { + protected void assertException(Method method, String pointcut, Class exceptionType, String message) { assertException(method, pointcut, null, null, exceptionType, message); } - protected void assertException( - Method method, String pointcut, String returning, String throwing, Class exceptionType, String message) { + protected void assertException(Method method, String pointcut, String returning, + String throwing, Class exceptionType, String message) { AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut); discoverer.setRaiseExceptions(true); discoverer.setReturningName(returning); discoverer.setThrowingName(throwing); - - try { - discoverer.getParameterNames(method); - fail("Expecting " + exceptionType.getName() + " with message '" + message + "'"); - } - catch (RuntimeException expected) { - assertEquals("Expecting exception of type " + exceptionType.getName(), - exceptionType, expected.getClass()); - assertEquals("Exception message does not match expected", message, expected.getMessage()); - } + assertThatExceptionOfType(exceptionType).isThrownBy(() -> + discoverer.getParameterNames(method)) + .withMessageContaining(message); } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java index 367821f54a4..fc85c27ee73 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java @@ -36,10 +36,13 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.subpkg.DeepBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -163,37 +166,25 @@ public class AspectJExpressionPointcutTests { @Test public void testFriendlyErrorOnNoLocationClassMatching() { AspectJExpressionPointcut pc = new AspectJExpressionPointcut(); - try { - pc.matches(ITestBean.class); - fail(); - } - catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("expression")); - } + assertThatIllegalStateException().isThrownBy(() -> + pc.matches(ITestBean.class)) + .withMessageContaining("expression"); } @Test public void testFriendlyErrorOnNoLocation2ArgMatching() { AspectJExpressionPointcut pc = new AspectJExpressionPointcut(); - try { - pc.matches(getAge, ITestBean.class); - fail(); - } - catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("expression")); - } + assertThatIllegalStateException().isThrownBy(() -> + pc.matches(getAge, ITestBean.class)) + .withMessageContaining("expression"); } @Test public void testFriendlyErrorOnNoLocation3ArgMatching() { AspectJExpressionPointcut pc = new AspectJExpressionPointcut(); - try { - pc.matches(getAge, ITestBean.class, (Object[]) null); - fail(); - } - catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("expression")); - } + assertThatIllegalStateException().isThrownBy(() -> + pc.matches(getAge, ITestBean.class, (Object[]) null)) + .withMessageContaining("expression"); } @@ -248,14 +239,8 @@ public class AspectJExpressionPointcutTests { @Test public void testInvalidExpression() { String expression = "execution(void org.springframework.tests.sample.beans.TestBean.setSomeNumber(Number) && args(Double)"; - - try { - getPointcut(expression).getClassFilter(); // call to getClassFilter forces resolution - fail("Invalid expression should throw IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - assertTrue(true); - } + assertThatIllegalArgumentException().isThrownBy( + getPointcut(expression)::getClassFilter); // call to getClassFilter forces resolution } private TestBean getAdvisedProxy(String pointcutExpression, CallCountingInterceptor interceptor) { @@ -285,14 +270,9 @@ public class AspectJExpressionPointcutTests { @Test public void testWithUnsupportedPointcutPrimitive() { String expression = "call(int org.springframework.tests.sample.beans.TestBean.getAge())"; - - try { - getPointcut(expression).getClassFilter(); // call to getClassFilter forces resolution... - fail("Should not support call pointcuts"); - } - catch (UnsupportedPointcutPrimitiveException ex) { - assertEquals("Should not support call pointcut", PointcutPrimitive.CALL, ex.getUnsupportedPrimitive()); - } + assertThatExceptionOfType(UnsupportedPointcutPrimitiveException.class).isThrownBy(() -> + getPointcut(expression).getClassFilter()) // call to getClassFilter forces resolution... + .satisfies(ex -> assertThat(ex.getUnsupportedPrimitive()).isEqualTo(PointcutPrimitive.CALL)); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java index 47591cfc227..0b42c4e7c75 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java @@ -37,12 +37,13 @@ import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -54,24 +55,14 @@ public class MethodInvocationProceedingJoinPointTests { @Test public void testingBindingWithJoinPoint() { - try { - AbstractAspectJAdvice.currentJoinPoint(); - fail("Needs to be bound by interceptor action"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy( + AbstractAspectJAdvice::currentJoinPoint); } @Test public void testingBindingWithProceedingJoinPoint() { - try { - AbstractAspectJAdvice.currentJoinPoint(); - fail("Needs to be bound by interceptor action"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy( + AbstractAspectJAdvice::currentJoinPoint); } @Test @@ -148,21 +139,8 @@ public class MethodInvocationProceedingJoinPointTests { SourceLocation sloc = AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(); assertEquals("Same source location must be returned on subsequent requests", sloc, AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()); assertEquals(TestBean.class, sloc.getWithinType()); - try { - sloc.getLine(); - fail("Can't get line number"); - } - catch (UnsupportedOperationException ex) { - // Expected - } - - try { - sloc.getFileName(); - fail("Can't get file name"); - } - catch (UnsupportedOperationException ex) { - // Expected - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getLine); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getFileName); } }); ITestBean itb = (ITestBean) pf.getProxy(); diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java index 0fda064d53f..ef5276a2ad5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java @@ -34,8 +34,8 @@ import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.core.OverridingClassLoader; import org.springframework.lang.Nullable; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Dave Syer @@ -112,13 +112,8 @@ public class TrickyAspectJPointcutExpressionTests { TestService bean = (TestService) factory.getProxy(); assertEquals(0, logAdvice.getCountThrows()); - try { - bean.sayHello(); - fail("Expected exception"); - } - catch (TestException ex) { - assertEquals(message, ex.getMessage()); - } + assertThatExceptionOfType(TestException.class).isThrownBy( + bean::sayHello).withMessageContaining(message); assertEquals(1, logAdvice.getCountThrows()); } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java index bcda6696f51..ec16c5187f1 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java @@ -26,6 +26,8 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.subpkg.DeepBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -38,10 +40,11 @@ import static org.junit.Assert.assertTrue; */ public class TypePatternClassFilterTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testInvalidPattern() { // should throw - pattern must be recognized as invalid - new TypePatternClassFilter("-"); + assertThatIllegalArgumentException().isThrownBy(() -> + new TypePatternClassFilter("-")); } @Test @@ -79,14 +82,16 @@ public class TypePatternClassFilterTests { assertTrue("matches Double",tpcf.matches(Double.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetTypePatternWithNullArgument() throws Exception { - new TypePatternClassFilter(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new TypePatternClassFilter(null)); } - @Test(expected = IllegalStateException.class) + @Test public void testInvocationOfMatchesMethodBlowsUpWhenNoTypePatternHasBeenSet() throws Exception { - new TypePatternClassFilter().matches(String.class); + assertThatIllegalStateException().isThrownBy(() -> + new TypePatternClassFilter().matches(String.class)); } } 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 07a1a97ec7e..6c083cb7947 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,14 +58,15 @@ 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.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; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Abstract tests for AspectJAdvisorFactory. @@ -86,26 +87,18 @@ public abstract class AbstractAspectJAdvisorFactoryTests { @Test public void testRejectsPerCflowAspect() { - try { - getFixture().getAdvisors( - new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(), "someBean")); - fail("Cannot accept cflow"); - } - catch (AopConfigException ex) { - assertTrue(ex.getMessage().contains("PERCFLOW")); - } + assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> + getFixture().getAdvisors( + new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(), "someBean"))) + .withMessageContaining("PERCFLOW"); } @Test public void testRejectsPerCflowBelowAspect() { - try { - getFixture().getAdvisors( - new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(), "someBean")); - fail("Cannot accept cflowbelow"); - } - catch (AopConfigException ex) { - assertTrue(ex.getMessage().contains("PERCFLOWBELOW")); - } + assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> + getFixture().getAdvisors( + new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(), "someBean"))) + .withMessageContaining("PERCFLOWBELOW"); } @Test @@ -365,12 +358,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { assertFalse(lockable2.locked()); notLockable2.setIntValue(1); lockable2.lock(); - try { - notLockable2.setIntValue(32); - fail(); - } - catch (IllegalStateException ex) { - } + assertThatIllegalStateException().isThrownBy(() -> + notLockable2.setIntValue(32)); assertTrue(lockable2.locked()); } @@ -400,13 +389,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { assertTrue("Already locked", lockable.locked()); lockable.lock(); assertTrue("Real target ignores locking", lockable.locked()); - try { - lockable.unlock(); - fail(); - } - catch (UnsupportedOperationException ex) { - // Ok - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + lockable.unlock()); } @Test @@ -463,13 +447,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { lockable.lock(); assertTrue(lockable.locked()); - try { - itb.setName("Else"); - fail("Should be locked"); - } - catch (IllegalStateException ex) { - // Ok - } + assertThatIllegalStateException().as("Should be locked").isThrownBy(() -> + itb.setName("Else")); lockable.unlock(); itb.setName("Tony"); } @@ -482,14 +461,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean")); assertEquals("One advice method was found", 1, advisors.size()); ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class); - - try { - itb.getAge(); - fail(); - } - catch (UnsupportedOperationException ex) { - assertSame(expectedException, ex); - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( + itb::getAge); } // TODO document this behaviour. @@ -502,14 +475,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean")); assertEquals("One advice method was found", 1, advisors.size()); ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class); - - try { - itb.getAge(); - fail(); - } - catch (UndeclaredThrowableException ex) { - assertSame(expectedException, ex.getCause()); - } + assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy( + itb::getAge).withCause(expectedException); } protected Object createProxy(Object target, List advisors, Class... interfaces) { @@ -555,17 +522,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { assertEquals("", echo.echo("")); assertEquals(1, afterReturningAspect.successCount); assertEquals(0, afterReturningAspect.failureCount); - - try { - echo.echo(new FileNotFoundException()); - fail(); - } - catch (FileNotFoundException ex) { - // Ok - } - catch (Exception ex) { - fail(); - } + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + echo.echo(new FileNotFoundException())); assertEquals(1, afterReturningAspect.successCount); assertEquals(1, afterReturningAspect.failureCount); assertEquals(afterReturningAspect.failureCount + afterReturningAspect.successCount, afterReturningAspect.afterCount); @@ -581,12 +539,14 @@ public abstract class AbstractAspectJAdvisorFactoryTests { itb.getAge(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDeclarePrecedenceNotSupported() { TestBean target = new TestBean(); - MetadataAwareAspectInstanceFactory aspectInstanceFactory = new SingletonMetadataAwareAspectInstanceFactory( - new DeclarePrecedenceShouldSucceed(), "someBean"); - createProxy(target, getFixture().getAdvisors(aspectInstanceFactory), ITestBean.class); + assertThatIllegalArgumentException().isThrownBy(() -> { + MetadataAwareAspectInstanceFactory aspectInstanceFactory = new SingletonMetadataAwareAspectInstanceFactory( + new DeclarePrecedenceShouldSucceed(), "someBean"); + createProxy(target, getFixture().getAdvisors(aspectInstanceFactory), ITestBean.class); + }); } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java index a769b30685e..5add0dfed2f 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java @@ -30,6 +30,8 @@ import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; /** @@ -39,24 +41,26 @@ import static org.junit.Assert.assertEquals; */ public class ArgumentBindingTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testBindingInPointcutUsedByAdvice() { TestBean tb = new TestBean(); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb); proxyFactory.addAspect(NamedPointcutWithArgs.class); ITestBean proxiedTestBean = proxyFactory.getProxy(); - proxiedTestBean.setName("Supercalifragalisticexpialidocious"); + assertThatIllegalArgumentException().isThrownBy(() -> + proxiedTestBean.setName("Supercalifragalisticexpialidocious")); } - @Test(expected = IllegalStateException.class) + @Test public void testAnnotationArgumentNameBinding() { TransactionalBean tb = new TransactionalBean(); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb); proxyFactory.addAspect(PointcutWithAnnotationArgument.class); ITransactionalBean proxiedTestBean = proxyFactory.getProxy(); - proxiedTestBean.doInTransaction(); + assertThatIllegalStateException().isThrownBy( + proxiedTestBean::doInTransaction); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java index ce60d4ab52d..6e5c41e8dd2 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java @@ -25,6 +25,7 @@ import org.springframework.aop.aspectj.AspectJExpressionPointcutTests; import org.springframework.aop.framework.AopConfigException; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; @@ -75,14 +76,16 @@ public class AspectJPointcutAdvisorTests { TestBean.class.getMethod("getSpouse"), TestBean.class)); } - @Test(expected = AopConfigException.class) + @Test public void testPerCflowTarget() { - testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowAspect.class); + assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> + testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowAspect.class)); } - @Test(expected = AopConfigException.class) + @Test public void testPerCflowBelowTarget() { - testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowBelowAspect.class); + assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> + testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowBelowAspect.class)); } private void testIllegalInstantiationModel(Class c) throws AopConfigException { diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java index 2b46ef1191c..2350c54251a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java @@ -23,6 +23,7 @@ import test.aop.PerTargetAspect; import org.springframework.aop.Pointcut; import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.ExceptionAspect; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; @@ -36,9 +37,10 @@ import static org.junit.Assert.assertTrue; */ public class AspectMetadataTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testNotAnAspect() { - new AspectMetadata(String.class,"someBean"); + assertThatIllegalArgumentException().isThrownBy(() -> + new AspectMetadata(String.class,"someBean")); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java index d361a41f5fe..c9e1a1e15c6 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java @@ -28,6 +28,7 @@ import test.aop.PerThisAspect; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -38,10 +39,11 @@ import static org.junit.Assert.assertTrue; */ public class AspectProxyFactoryTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNonAspect() { AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); - proxyFactory.addAspect(TestBean.class); + assertThatIllegalArgumentException().isThrownBy(() -> + proxyFactory.addAspect(TestBean.class)); } @Test @@ -74,10 +76,11 @@ public class AspectProxyFactoryTests { assertEquals(2, proxy1.getAge()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithInstanceWithNonAspect() throws Exception { AspectJProxyFactory pf = new AspectJProxyFactory(); - pf.addAspect(new TestBean()); + assertThatIllegalArgumentException().isThrownBy(() -> + pf.addAspect(new TestBean())); } @Test @@ -111,10 +114,11 @@ public class AspectProxyFactoryTests { assertEquals(target.getAge() * multiple, serializedProxy.getAge()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNonSingletonAspectInstance() throws Exception { AspectJProxyFactory pf = new AspectJProxyFactory(); - pf.addAspect(new PerThisAspect()); + assertThatIllegalArgumentException().isThrownBy(() -> + pf.addAspect(new PerThisAspect())); } @Test // SPR-13328 diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java index 6a90b737875..d447b9bdc84 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java @@ -23,8 +23,7 @@ import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -35,28 +34,20 @@ public class AopNamespaceHandlerPointcutErrorTests { @Test public void testDuplicatePointcutConfig() { - try { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions( - qualifiedResource(getClass(), "pointcutDuplication.xml")); - fail("parsing should have caused a BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - assertTrue(ex.contains(BeanDefinitionParsingException.class)); - } + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(bf).loadBeanDefinitions( + qualifiedResource(getClass(), "pointcutDuplication.xml"))) + .satisfies(ex -> ex.contains(BeanDefinitionParsingException.class)); } @Test public void testMissingPointcutConfig() { - try { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions( - qualifiedResource(getClass(), "pointcutMissing.xml")); - fail("parsing should have caused a BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - assertTrue(ex.contains(BeanDefinitionParsingException.class)); - } + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(bf).loadBeanDefinitions( + qualifiedResource(getClass(), "pointcutMissing.xml"))) + .satisfies(ex -> ex.contains(BeanDefinitionParsingException.class)); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java index 90646bd6f72..47584a2d718 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java @@ -26,6 +26,7 @@ import org.springframework.aop.SpringProxy; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -125,11 +126,12 @@ public class AopProxyUtilsTests { assertEquals(Comparable.class, userInterfaces[1]); } - @Test(expected = IllegalArgumentException.class) + @Test public void testProxiedUserInterfacesWithNoInterface() { Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[0], (proxy1, method, args) -> null); - AopProxyUtils.proxiedUserInterfaces(proxy); + assertThatIllegalArgumentException().isThrownBy(() -> + AopProxyUtils.proxiedUserInterfaces(proxy)); } } 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 76332442c28..e671f0ad69a 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,6 +42,7 @@ 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.assertThatExceptionOfType; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @@ -49,7 +50,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Also tests AdvisedSupport and ProxyCreatorSupport superclasses. @@ -277,13 +277,9 @@ public class ProxyFactoryTests { assertTrue(config.getAdvisors().length == oldCount); - try { - // Existing reference will fail - ts.getTimeStamp(); - fail("Existing object won't implement this interface any more"); - } - catch (RuntimeException ex) { - } + assertThatExceptionOfType(RuntimeException.class) + .as("Existing object won't implement this interface any more") + .isThrownBy(ts::getTimeStamp); // Existing reference will fail assertFalse("Should no longer implement TimeStamped", config.getProxy() instanceof TimeStamped); diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java index 7fa1e0308c6..551540073c4 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java @@ -28,8 +28,9 @@ import org.junit.Test; import org.springframework.aop.ThrowsAdvice; import org.springframework.tests.aop.advice.MethodCounter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -39,10 +40,11 @@ import static org.mockito.Mockito.mock; */ public class ThrowsAdviceInterceptorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testNoHandlerMethods() { // should require one handler method at least - new ThrowsAdviceInterceptor(new Object()); + assertThatIllegalArgumentException().isThrownBy(() -> + new ThrowsAdviceInterceptor(new Object())); } @Test @@ -64,13 +66,9 @@ public class ThrowsAdviceInterceptorTests { Exception ex = new Exception(); MethodInvocation mi = mock(MethodInvocation.class); given(mi.proceed()).willThrow(ex); - try { - ti.invoke(mi); - fail(); - } - catch (Exception caught) { - assertEquals(ex, caught); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + ti.invoke(mi)) + .isSameAs(ex); assertEquals(0, th.getCalls()); } @@ -83,13 +81,9 @@ public class ThrowsAdviceInterceptorTests { given(mi.getMethod()).willReturn(Object.class.getMethod("hashCode")); given(mi.getThis()).willReturn(new Object()); given(mi.proceed()).willThrow(ex); - try { - ti.invoke(mi); - fail(); - } - catch (Exception caught) { - assertEquals(ex, caught); - } + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + ti.invoke(mi)) + .isSameAs(ex); assertEquals(1, th.getCalls()); assertEquals(1, th.getCalls("ioException")); } @@ -102,13 +96,9 @@ public class ThrowsAdviceInterceptorTests { ConnectException ex = new ConnectException(""); MethodInvocation mi = mock(MethodInvocation.class); given(mi.proceed()).willThrow(ex); - try { - ti.invoke(mi); - fail(); - } - catch (Exception caught) { - assertEquals(ex, caught); - } + assertThatExceptionOfType(ConnectException.class).isThrownBy(() -> + ti.invoke(mi)) + .isSameAs(ex); assertEquals(1, th.getCalls()); assertEquals(1, th.getCalls("remoteException")); } @@ -131,13 +121,9 @@ public class ThrowsAdviceInterceptorTests { ConnectException ex = new ConnectException(""); MethodInvocation mi = mock(MethodInvocation.class); given(mi.proceed()).willThrow(ex); - try { - ti.invoke(mi); - fail(); - } - catch (Throwable caught) { - assertEquals(t, caught); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + ti.invoke(mi)) + .isSameAs(t); assertEquals(1, th.getCalls()); assertEquals(1, th.getCalls("remoteException")); } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java index 7de7d4ebb2a..5d63b554aa3 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java @@ -20,7 +20,7 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -36,52 +36,60 @@ import static org.mockito.Mockito.verify; */ public class CustomizableTraceInterceptorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testSetEmptyEnterMessage() { // Must not be able to set empty enter message - new CustomizableTraceInterceptor().setEnterMessage(""); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setEnterMessage("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetEnterMessageWithReturnValuePlaceholder() { // Must not be able to set enter message with return value placeholder - new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetEnterMessageWithExceptionPlaceholder() { // Must not be able to set enter message with exception placeholder - new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetEnterMessageWithInvocationTimePlaceholder() { // Must not be able to set enter message with invocation time placeholder - new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetEmptyExitMessage() { // Must not be able to set empty exit message - new CustomizableTraceInterceptor().setExitMessage(""); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setExitMessage("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetExitMessageWithExceptionPlaceholder() { // Must not be able to set exit message with exception placeholder - new CustomizableTraceInterceptor().setExitMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setExitMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetEmptyExceptionMessage() { // Must not be able to set empty exception message - new CustomizableTraceInterceptor().setExceptionMessage(""); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setExceptionMessage("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetExceptionMethodWithReturnValuePlaceholder() { // Must not be able to set exception message with return value placeholder - new CustomizableTraceInterceptor().setExceptionMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomizableTraceInterceptor().setExceptionMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE)); } @Test @@ -114,12 +122,8 @@ public class CustomizableTraceInterceptorTests { given(log.isTraceEnabled()).willReturn(true); CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log); - try { - interceptor.invoke(methodInvocation); - fail("Must have propagated the IllegalArgumentException."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + interceptor.invoke(methodInvocation)); verify(log).trace(anyString()); verify(log).trace(anyString(), eq(exception)); diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java index 0f9c2b48270..47d092db3a5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java @@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -64,12 +64,8 @@ public class DebugInterceptorTests { given(log.isTraceEnabled()).willReturn(true); DebugInterceptor interceptor = new StubDebugInterceptor(log); - try { - interceptor.invoke(methodInvocation); - fail("Must have propagated the IllegalArgumentException."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + interceptor.invoke(methodInvocation)); checkCallCountTotal(interceptor); verify(log).trace(anyString()); diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java index b499fa610e3..dfafaae31b3 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java @@ -23,9 +23,9 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -69,12 +69,8 @@ public class JamonPerformanceMonitorInterceptorTests { given(mi.getMethod()).willReturn(String.class.getMethod("toString")); given(mi.proceed()).willThrow(new IllegalArgumentException()); - try { - interceptor.invokeUnderTrace(mi, log); - fail("Must have propagated the IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + interceptor.invokeUnderTrace(mi, log)); assertEquals("Monitors must exist for the method invocation and 2 exceptions", 3, MonitorFactory.getNumRows()); diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java index aa9385ae178..c406ab89800 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java @@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -70,12 +70,8 @@ public class PerformanceMonitorInterceptorTests { Log log = mock(Log.class); PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true); - try { - interceptor.invokeUnderTrace(mi, log); - fail("Must have propagated the IllegalArgumentException."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + interceptor.invokeUnderTrace(mi, log)); verify(log).trace(anyString()); } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java index 86cf08db945..b98e25babd1 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java @@ -20,7 +20,7 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -61,13 +61,8 @@ public class SimpleTraceInterceptorTests { Log log = mock(Log.class); final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true); - - try { - interceptor.invokeUnderTrace(mi, log); - fail("Must have propagated the IllegalArgumentException."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + interceptor.invokeUnderTrace(mi, log)); verify(log).trace(anyString()); verify(log).trace(anyString(), eq(exception)); diff --git a/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java b/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java index d229ff3a0c5..ef0291ea421 100644 --- a/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java @@ -20,6 +20,7 @@ import org.junit.Test; import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -33,24 +34,28 @@ public class DefaultScopedObjectTests { private static final String GOOD_BEAN_NAME = "foo"; - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullBeanFactory() throws Exception { - new DefaultScopedObject(null, GOOD_BEAN_NAME); + assertThatIllegalArgumentException().isThrownBy(() -> + new DefaultScopedObject(null, GOOD_BEAN_NAME)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullTargetBeanName() throws Exception { - testBadTargetBeanName(null); + assertThatIllegalArgumentException().isThrownBy(() -> + testBadTargetBeanName(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithEmptyTargetBeanName() throws Exception { - testBadTargetBeanName(""); + assertThatIllegalArgumentException().isThrownBy(() -> + testBadTargetBeanName("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithJustWhitespacedTargetBeanName() throws Exception { - testBadTargetBeanName(" "); + assertThatIllegalArgumentException().isThrownBy(() -> + testBadTargetBeanName(" ")); } private static void testBadTargetBeanName(final String badTargetBeanName) { 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 bfc52d73443..e61808e39f3 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,6 +34,7 @@ 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.assertThatIllegalArgumentException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; @@ -49,10 +50,11 @@ import static org.mockito.Mockito.mock; */ public class DelegatingIntroductionInterceptorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testNullTarget() throws Exception { // Shouldn't accept null target - new DelegatingIntroductionInterceptor(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new DelegatingIntroductionInterceptor(null)); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java index bcf66b1d6d2..20ea139e51b 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java @@ -31,9 +31,8 @@ import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -110,19 +109,11 @@ public class HotSwappableTargetSourceTests { @Test public void testRejectsSwapToNull() { HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper"); - IllegalArgumentException aopex = null; - try { - swapper.swap(null); - fail("Shouldn't be able to swap to invalid value"); - } - catch (IllegalArgumentException ex) { - // Ok - aopex = ex; - } - + assertThatIllegalArgumentException().as("Shouldn't be able to swap to invalid value").isThrownBy(() -> + swapper.swap(null)) + .withMessageContaining("null"); // It shouldn't be corrupted, it should still work testBasicFunctionality(); - assertTrue(aopex.getMessage().contains("null")); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java index 5c1fa599f5c..75e3f4e7776 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java @@ -26,7 +26,6 @@ import org.springframework.tests.sample.beans.SideEffectBean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -154,12 +153,7 @@ public class ThreadLocalTargetSourceTests { source.destroy(); // try second time - try { - source.getTarget(); - } - catch (NullPointerException ex) { - fail("Should not throw NPE"); - } + source.getTarget(); // Should not throw NPE } } 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 efff0e7a48d..d90e50a853d 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 @@ -43,7 +43,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; /** * Unit tests for {@link AnnotationAsyncExecutionAspect}. @@ -176,18 +175,12 @@ public class AnnotationAsyncExecutionAspectTests { try { assertFalse("Handler should not have been called", exceptionHandler.isCalled()); ClassWithException obj = new ClassWithException(); - try { - obj.failWithVoid(); - exceptionHandler.await(3000); - exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); - } - catch (Exception ex) { - fail("No unexpected exception should have been received but got " + ex.getMessage()); - } + obj.failWithVoid(); + exceptionHandler.await(3000); + exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); } finally { AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(defaultExceptionHandler); - } } @@ -215,7 +208,7 @@ public class AnnotationAsyncExecutionAspectTests { wait(WAIT_TIME); } catch (InterruptedException ex) { - fail("Didn't finish the async job in " + WAIT_TIME + " milliseconds"); + throw new AssertionError("Didn't finish the async job in " + WAIT_TIME + " milliseconds"); } } } diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java index 747b1b46737..6f2d42c2489 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java @@ -30,8 +30,9 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.transaction.CallCountingTransactionManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIOException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Stephane Nicoll @@ -59,13 +60,9 @@ public class JtaTransactionAspectsTests { public void matchingRollbackOnApplied() throws Throwable { assertEquals(0, this.txManager.begun); InterruptedException test = new InterruptedException(); - try { - new JtaAnnotationPublicAnnotatedMember().echo(test); - fail("Should have thrown an exception"); - } - catch (Throwable throwable) { - assertEquals("wrong exception", test, throwable); - } + assertThatExceptionOfType(InterruptedException.class).isThrownBy(() -> + new JtaAnnotationPublicAnnotatedMember().echo(test)) + .isSameAs(test); assertEquals(1, this.txManager.rollbacks); assertEquals(0, this.txManager.commits); } @@ -74,13 +71,9 @@ public class JtaTransactionAspectsTests { public void nonMatchingRollbackOnApplied() throws Throwable { assertEquals(0, this.txManager.begun); IOException test = new IOException(); - try { - new JtaAnnotationPublicAnnotatedMember().echo(test); - fail("Should have thrown an exception"); - } - catch (Throwable throwable) { - assertEquals("wrong exception", test, throwable); - } + assertThatIOException().isThrownBy(() -> + new JtaAnnotationPublicAnnotatedMember().echo(test)) + .isSameAs(test); assertEquals(1, this.txManager.commits); assertEquals(0, this.txManager.rollbacks); } diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java index 0e3dbf457bb..05c6132fa14 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java @@ -21,9 +21,8 @@ import org.junit.Test; import org.springframework.tests.transaction.CallCountingTransactionManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -104,50 +103,34 @@ public class TransactionAspectTests { @Test public void defaultCommitOnAnnotatedClass() throws Throwable { - final Exception ex = new Exception(); - try { - testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false); - fail("Should have thrown Exception"); - } - catch (Exception ex2) { - assertSame(ex, ex2); - } + Exception ex = new Exception(); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false)) + .isSameAs(ex); } @Test public void defaultRollbackOnAnnotatedClass() throws Throwable { - final RuntimeException ex = new RuntimeException(); - try { - testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true); - fail("Should have thrown RuntimeException"); - } - catch (RuntimeException ex2) { - assertSame(ex, ex2); - } + RuntimeException ex = new RuntimeException(); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true)) + .isSameAs(ex); } @Test public void defaultCommitOnSubclassOfAnnotatedClass() throws Throwable { - final Exception ex = new Exception(); - try { - testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false); - fail("Should have thrown Exception"); - } - catch (Exception ex2) { - assertSame(ex, ex2); - } + Exception ex = new Exception(); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false)) + .isSameAs(ex); } @Test public void defaultCommitOnSubclassOfClassWithTransactionalMethodAnnotated() throws Throwable { - final Exception ex = new Exception(); - try { - testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false); - fail("Should have thrown Exception"); - } - catch (Exception ex2) { - assertSame(ex, ex2); - } + Exception ex = new Exception(); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false)) + .isSameAs(ex); } @Test @@ -180,18 +163,9 @@ public class TransactionAspectTests { protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable { txManager.clear(); assertEquals(0, txManager.begun); - try { - toc.performTransactionalOperation(); - } - catch (Throwable ex) { - if (expected == null) { - fail("Expected " + expected); - } - assertSame(expected, ex); - } - finally { - assertEquals(0, txManager.begun); - } + assertThatExceptionOfType(Throwable.class).isThrownBy( + toc::performTransactionalOperation).isSameAs(expected); + assertEquals(0, txManager.begun); } 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 df2578de388..4df802af316 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java @@ -58,6 +58,7 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.StopWatch; 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; @@ -69,7 +70,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Shared tests for property accessors. @@ -90,13 +90,8 @@ public abstract class AbstractPropertyAccessorTests { @Test public void createWithNullTarget() { - try { - createAccessor(null); - fail("Must throw an exception when constructed with null object"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + createAccessor(null)); } @Test @@ -240,15 +235,12 @@ public abstract class AbstractPropertyAccessorTests { Person target = createPerson("John", "London", "UK"); target.address = null; AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.getPropertyValue("address.country.name"); - fail("Should have failed to get value with null intermediate path"); - } - catch (NullValueInNestedPathException e) { - assertEquals("address", e.getPropertyName()); - assertEquals(Person.class, e.getBeanClass()); - } + assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() -> + accessor.getPropertyValue("address.country.name")) + .satisfies(ex -> { + assertThat(ex.getPropertyName()).isEqualTo("address"); + assertThat(ex.getBeanClass()).isEqualTo(Person.class); + }); } @Test @@ -275,15 +267,12 @@ public abstract class AbstractPropertyAccessorTests { public void getUnknownProperty() { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.getPropertyValue("foo"); - fail("Should have failed to get an unknown property."); - } - catch (NotReadablePropertyException e) { - assertEquals(Simple.class, e.getBeanClass()); - assertEquals("foo", e.getPropertyName()); - } + assertThatExceptionOfType(NotReadablePropertyException.class).isThrownBy(() -> + accessor.getPropertyValue("foo")) + .satisfies(ex -> { + assertThat(ex.getBeanClass()).isEqualTo(Simple.class); + assertThat(ex.getPropertyName()).isEqualTo("foo"); + }); } @Test @@ -398,31 +387,22 @@ public abstract class AbstractPropertyAccessorTests { Person target = createPerson("John", "Paris", "FR"); target.address.country = null; AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.setPropertyValue("address.country.name", "UK"); - fail("Should have failed to set value with intermediate null value"); - } - catch (NullValueInNestedPathException e) { - assertEquals("address.country", e.getPropertyName()); - assertEquals(Person.class, e.getBeanClass()); - } - assertThat(target.address.country, is(nullValue())); // Not touched + assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() -> + accessor.setPropertyValue("address.country.name", "UK")) + .satisfies(ex -> { + assertThat(ex.getPropertyName()).isEqualTo("address.country"); + assertThat(ex.getBeanClass()).isEqualTo(Person.class); + }); + assertThat(target.address.country).isNull(); // Not touched } @Test public void setAnotherPropertyIntermediatePropertyIsNull() throws Exception { ITestBean target = new TestBean("rod", 31); AbstractPropertyAccessor accessor = createAccessor(target); - try { - accessor.setPropertyValue("spouse.age", new Integer(31)); - fail("Shouldn't have succeeded with null path"); - } - catch (NullValueInNestedPathException ex) { - // expected - assertTrue("it was the spouse property that was null, not " + ex.getPropertyName(), - ex.getPropertyName().equals("spouse")); - } + assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() -> + accessor.setPropertyValue("spouse.age", new Integer(31))) + .satisfies(ex -> assertThat(ex.getPropertyName()).isEqualTo("spouse")); } @Test @@ -481,18 +461,13 @@ public abstract class AbstractPropertyAccessorTests { String name = "Tony"; target.setAge(age); target.setName(name); - try { - AbstractPropertyAccessor accessor = createAccessor(target); - assertTrue("age is OK", target.getAge() == age); - assertTrue("name is OK", name.equals(target.getName())); - accessor.setPropertyValues(new MutablePropertyValues()); - // Check its unchanged - assertTrue("age is OK", target.getAge() == age); - assertTrue("name is OK", name.equals(target.getName())); - } - catch (BeansException ex) { - fail("Shouldn't throw exception when everything is valid"); - } + AbstractPropertyAccessor accessor = createAccessor(target); + assertTrue("age is OK", target.getAge() == age); + assertTrue("name is OK", name.equals(target.getName())); + accessor.setPropertyValues(new MutablePropertyValues()); + // Check its unchanged + assertTrue("age is OK", target.getAge() == age); + assertTrue("name is OK", name.equals(target.getName())); } @@ -502,20 +477,15 @@ public abstract class AbstractPropertyAccessorTests { String newName = "tony"; int newAge = 65; String newTouchy = "valid"; - try { - AbstractPropertyAccessor accessor = createAccessor(target); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue(new PropertyValue("age", newAge)); - pvs.addPropertyValue(new PropertyValue("name", newName)); - pvs.addPropertyValue(new PropertyValue("touchy", newTouchy)); - accessor.setPropertyValues(pvs); - assertTrue("Name property should have changed", target.getName().equals(newName)); - assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy)); - assertTrue("Age property should have changed", target.getAge() == newAge); - } - catch (BeansException ex) { - fail("Shouldn't throw exception when everything is valid"); - } + AbstractPropertyAccessor accessor = createAccessor(target); + MutablePropertyValues pvs = new MutablePropertyValues(); + pvs.addPropertyValue(new PropertyValue("age", newAge)); + pvs.addPropertyValue(new PropertyValue("name", newName)); + pvs.addPropertyValue(new PropertyValue("touchy", newTouchy)); + accessor.setPropertyValues(pvs); + assertTrue("Name property should have changed", target.getName().equals(newName)); + assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy)); + assertTrue("Age property should have changed", target.getAge() == newAge); } @Test @@ -524,34 +494,24 @@ public abstract class AbstractPropertyAccessorTests { String newName = "tony"; int newAge = 65; String newTouchy = "valid"; - try { - AbstractPropertyAccessor accessor = createAccessor(target); - accessor.setPropertyValue("age", new Integer(newAge)); - accessor.setPropertyValue(new PropertyValue("name", newName)); - accessor.setPropertyValue(new PropertyValue("touchy", newTouchy)); - assertTrue("Name property should have changed", target.getName().equals(newName)); - assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy)); - assertTrue("Age property should have changed", target.getAge() == newAge); - } - catch (BeansException ex) { - fail("Shouldn't throw exception when everything is valid"); - } + AbstractPropertyAccessor accessor = createAccessor(target); + accessor.setPropertyValue("age", new Integer(newAge)); + accessor.setPropertyValue(new PropertyValue("name", newName)); + accessor.setPropertyValue(new PropertyValue("touchy", newTouchy)); + assertTrue("Name property should have changed", target.getName().equals(newName)); + assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy)); + assertTrue("Age property should have changed", target.getAge() == newAge); } @Test public void setPropertyIsReflectedImmediately() { TestBean target = new TestBean(); int newAge = 33; - try { - AbstractPropertyAccessor accessor = createAccessor(target); - target.setAge(newAge); - Object bwAge = accessor.getPropertyValue("age"); - assertTrue("Age is an integer", bwAge instanceof Integer); - assertTrue("Bean wrapper must pick up changes", (int) bwAge == newAge); - } - catch (Exception ex) { - fail("Shouldn't throw exception when everything is valid"); - } + AbstractPropertyAccessor accessor = createAccessor(target); + target.setAge(newAge); + Object bwAge = accessor.getPropertyValue("age"); + assertTrue("Age is an integer", bwAge instanceof Integer); + assertTrue("Bean wrapper must pick up changes", (int) bwAge == newAge); } @Test @@ -645,20 +605,13 @@ public abstract class AbstractPropertyAccessorTests { public void setNumberProperties() { NumberTestBean target = new NumberTestBean(); AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.setPropertyValue("short2", "2"); - accessor.setPropertyValue("int2", "8"); - accessor.setPropertyValue("long2", "6"); - accessor.setPropertyValue("bigInteger", "3"); - accessor.setPropertyValue("float2", "8.1"); - accessor.setPropertyValue("double2", "6.1"); - accessor.setPropertyValue("bigDecimal", "4.0"); - } - catch (BeansException ex) { - fail("Should not throw BeansException: " + ex.getMessage()); - } - + accessor.setPropertyValue("short2", "2"); + accessor.setPropertyValue("int2", "8"); + accessor.setPropertyValue("long2", "6"); + accessor.setPropertyValue("bigInteger", "3"); + accessor.setPropertyValue("float2", "8.1"); + accessor.setPropertyValue("double2", "6.1"); + accessor.setPropertyValue("bigDecimal", "4.0"); assertTrue("Correct short2 value", new Short("2").equals(accessor.getPropertyValue("short2"))); assertTrue("Correct short2 value", new Short("2").equals(target.getShort2())); assertTrue("Correct int2 value", new Integer("8").equals(accessor.getPropertyValue("int2"))); @@ -679,20 +632,13 @@ public abstract class AbstractPropertyAccessorTests { public void setNumberPropertiesWithCoercion() { NumberTestBean target = new NumberTestBean(); AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.setPropertyValue("short2", new Integer(2)); - accessor.setPropertyValue("int2", new Long(8)); - accessor.setPropertyValue("long2", new BigInteger("6")); - accessor.setPropertyValue("bigInteger", new Integer(3)); - accessor.setPropertyValue("float2", new Double(8.1)); - accessor.setPropertyValue("double2", new BigDecimal(6.1)); - accessor.setPropertyValue("bigDecimal", new Float(4.0)); - } - catch (BeansException ex) { - fail("Should not throw BeansException: " + ex.getMessage()); - } - + accessor.setPropertyValue("short2", new Integer(2)); + accessor.setPropertyValue("int2", new Long(8)); + accessor.setPropertyValue("long2", new BigInteger("6")); + accessor.setPropertyValue("bigInteger", new Integer(3)); + accessor.setPropertyValue("float2", new Double(8.1)); + accessor.setPropertyValue("double2", new BigDecimal(6.1)); + accessor.setPropertyValue("bigDecimal", new Float(4.0)); assertTrue("Correct short2 value", new Short("2").equals(accessor.getPropertyValue("short2"))); assertTrue("Correct short2 value", new Short("2").equals(target.getShort2())); assertTrue("Correct int2 value", new Integer("8").equals(accessor.getPropertyValue("int2"))); @@ -770,13 +716,8 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("autowire", " BY_TYPE "); assertEquals(Autowire.BY_TYPE, target.getAutowire()); - try { - accessor.setPropertyValue("autowire", "NHERITED"); - fail("Should have thrown TypeMismatchException"); - } - catch (TypeMismatchException ex) { - // expected - } + assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> + accessor.setPropertyValue("autowire", "NHERITED")); } @Test @@ -1392,24 +1333,19 @@ public abstract class AbstractPropertyAccessorTests { } }); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.add("map[key1]", "rod"); - pvs.add("map[key2]", "rob"); - accessor.setPropertyValues(pvs); + MutablePropertyValues goodValues = new MutablePropertyValues(); + goodValues.add("map[key1]", "rod"); + goodValues.add("map[key2]", "rob"); + accessor.setPropertyValues(goodValues); assertEquals("rod", ((TestBean) target.getMap().get("key1")).getName()); assertEquals("rob", ((TestBean) target.getMap().get("key2")).getName()); - pvs = new MutablePropertyValues(); - pvs.add("map[key1]", "rod"); - pvs.add("map[key2]", ""); - try { - accessor.setPropertyValues(pvs); - fail("Should have thrown TypeMismatchException"); - } - catch (PropertyBatchUpdateException ex) { - PropertyAccessException pae = ex.getPropertyAccessException("map[key2]"); - assertTrue(pae instanceof TypeMismatchException); - } + MutablePropertyValues badValues = new MutablePropertyValues(); + badValues.add("map[key1]", "rod"); + badValues.add("map[key2]", ""); + assertThatExceptionOfType(PropertyBatchUpdateException.class).isThrownBy(() -> + accessor.setPropertyValues(badValues)) + .satisfies(ex -> assertThat(ex.getPropertyAccessException("map[key2]")).isInstanceOf(TypeMismatchException.class)); } @Test @@ -1480,47 +1416,34 @@ public abstract class AbstractPropertyAccessorTests { public void setUnknownProperty() { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.setPropertyValue("name1", "value"); - fail("Should have failed to set an unknown property."); - } - catch (NotWritablePropertyException e) { - assertEquals(Simple.class, e.getBeanClass()); - assertEquals("name1", e.getPropertyName()); - assertEquals("Invalid number of possible matches", 1, e.getPossibleMatches().length); - assertEquals("name", e.getPossibleMatches()[0]); - } + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + accessor.setPropertyValue("name1", "value")) + .satisfies(ex -> { + assertThat(ex.getBeanClass()).isEqualTo(Simple.class); + assertThat(ex.getPropertyName()).isEqualTo("name1"); + assertThat(ex.getPossibleMatches()).containsExactly("name"); + }); } @Test public void setUnknownPropertyWithPossibleMatches() { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - - try { - accessor.setPropertyValue("foo", "value"); - fail("Should have failed to set an unknown property."); - } - catch (NotWritablePropertyException e) { - assertEquals(Simple.class, e.getBeanClass()); - assertEquals("foo", e.getPropertyName()); - } + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + accessor.setPropertyValue("foo", "value")) + .satisfies(ex -> { + assertThat(ex.getBeanClass()).isEqualTo(Simple.class); + assertThat(ex.getPropertyName()).isEqualTo("foo"); + }); } @Test public void setUnknownOptionalProperty() { Simple target = new Simple("John", 2); AbstractPropertyAccessor accessor = createAccessor(target); - - try { - PropertyValue value = new PropertyValue("foo", "value"); - value.setOptional(true); - accessor.setPropertyValue(value); - } - catch (NotWritablePropertyException e) { - fail("Should not have failed to set an unknown optional property."); - } + PropertyValue value = new PropertyValue("foo", "value"); + value.setOptional(true); + accessor.setPropertyValue(value); } @Test @@ -1535,30 +1458,17 @@ public abstract class AbstractPropertyAccessorTests { @Test public void setPropertyTypeMismatch() { TestBean target = new TestBean(); - try { - AbstractPropertyAccessor accessor = createAccessor(target); - accessor.setPropertyValue("age", "foobar"); - fail("Should throw exception on type mismatch"); - } - catch (TypeMismatchException ex) { - // expected - } + AbstractPropertyAccessor accessor = createAccessor(target); + assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> + accessor.setPropertyValue("age", "foobar")); } @Test public void setEmptyValueForPrimitiveProperty() { TestBean target = new TestBean(); - try { - AbstractPropertyAccessor accessor = createAccessor(target); - accessor.setPropertyValue("age", ""); - fail("Should throw exception on type mismatch"); - } - catch (TypeMismatchException ex) { - // expected - } - catch (Exception ex) { - fail("Shouldn't throw exception other than Type mismatch"); - } + AbstractPropertyAccessor accessor = createAccessor(target); + assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> + accessor.setPropertyValue("age", "")); } @Test @@ -1580,14 +1490,8 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValues(pvs, true); assertTrue("Set valid and ignored invalid", target.getName().equals("rod")); - try { - // Don't ignore: should fail - accessor.setPropertyValues(pvs, false); - fail("Shouldn't have ignored invalid updates"); - } - catch (NotWritablePropertyException ex) { - // OK: but which exception?? - } + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + accessor.setPropertyValues(pvs, false)); // Don't ignore: should fail } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java index 5728eef71c9..d1a77392241 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java @@ -33,6 +33,8 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -49,14 +51,16 @@ import static org.junit.Assert.assertTrue; */ public class BeanUtilsTests { - @Test(expected = FatalBeanException.class) + @Test public void testInstantiateClassGivenInterface() { - BeanUtils.instantiateClass(List.class); + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + BeanUtils.instantiateClass(List.class)); } - @Test(expected = FatalBeanException.class) + @Test public void testInstantiateClassGivenClassWithoutDefaultConstructor() { - BeanUtils.instantiateClass(CustomDateEditor.class); + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + BeanUtils.instantiateClass(CustomDateEditor.class)); } @Test // gh-22531 @@ -78,10 +82,11 @@ public class BeanUtilsTests { assertEquals("foo", bean.getValue()); } - @Test(expected = BeanInstantiationException.class) // gh-22531 + @Test // gh-22531 public void testInstantiateClassWithMoreArgsThanParameters() throws NoSuchMethodException { Constructor ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class); - BeanUtils.instantiateClass(ctor, null, null, "foo", null); + assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() -> + BeanUtils.instantiateClass(ctor, null, null, "foo", null)); } @Test @@ -221,14 +226,16 @@ public class BeanUtilsTests { assertSignatureEquals(desiredMethod, "doSomething()"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testResolveInvalidSignatureEndParen() { - BeanUtils.resolveSignature("doSomething(", MethodSignatureBean.class); + assertThatIllegalArgumentException().isThrownBy(() -> + BeanUtils.resolveSignature("doSomething(", MethodSignatureBean.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testResolveInvalidSignatureStartParen() { - BeanUtils.resolveSignature("doSomething)", MethodSignatureBean.class); + assertThatIllegalArgumentException().isThrownBy(() -> + BeanUtils.resolveSignature("doSomething)", MethodSignatureBean.class)); } @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 2e541709cee..28971c35ae1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java @@ -22,13 +22,12 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; +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; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Keith Donald @@ -58,9 +57,10 @@ public class BeanWrapperAutoGrowingTests { assertEquals("test", bean.getNested().getProp()); } - @Test(expected = NullValueInNestedPathException.class) + @Test public void getPropertyValueNullValueInNestedPathNoDefaultConstructor() { - wrapper.getPropertyValue("nestedNoConstructor.prop"); + assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() -> + wrapper.getPropertyValue("nestedNoConstructor.prop")); } @Test @@ -129,14 +129,9 @@ public class BeanWrapperAutoGrowingTests { @Test public void getPropertyValueAutoGrowListFailsAgainstLimit() { wrapper.setAutoGrowCollectionLimit(2); - try { - assertNotNull(wrapper.getPropertyValue("list[4]")); - fail("Should have thrown InvalidPropertyException"); - } - catch (InvalidPropertyException ex) { - // expected - assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); - } + assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() -> + assertNotNull(wrapper.getPropertyValue("list[4]"))) + .withRootCauseInstanceOf(IndexOutOfBoundsException.class); } @Test @@ -146,9 +141,10 @@ public class BeanWrapperAutoGrowingTests { assertThat(bean.getMultiList().get(0).get(0), instanceOf(Bean.class)); } - @Test(expected = InvalidPropertyException.class) + @Test public void getPropertyValueAutoGrowListNotParameterized() { - wrapper.getPropertyValue("listNotParameterized[0]"); + assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() -> + wrapper.getPropertyValue("listNotParameterized[0]")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java index 24ac84454a5..8768b3cf124 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -39,9 +39,9 @@ import org.springframework.tests.sample.beans.GenericIntegerBean; import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -81,13 +81,9 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(gb); Set input = new HashSet<>(); input.add(new TestBean()); - try { - bw.setPropertyValue("integerSet", input); - fail("Should have thrown TypeMismatchException"); - } - catch (TypeMismatchException ex) { - assertTrue(ex.getMessage().contains("java.lang.Integer")); - } + assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> + bw.setPropertyValue("integerSet", input)) + .withMessageContaining("java.lang.Integer"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java index c135730bfeb..bacdf4cff20 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java @@ -24,12 +24,12 @@ 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.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Specific {@link BeanWrapperImpl} tests. @@ -82,38 +82,30 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { TestBean target = new TestBean(); String newName = "tony"; String invalidTouchy = ".valid"; - try { - BeanWrapper accessor = createAccessor(target); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue(new PropertyValue("age", "foobar")); - pvs.addPropertyValue(new PropertyValue("name", newName)); - pvs.addPropertyValue(new PropertyValue("touchy", invalidTouchy)); - accessor.setPropertyValues(pvs); - fail("Should throw exception when everything is valid"); - } - catch (PropertyBatchUpdateException ex) { - assertTrue("Must contain 2 exceptions", ex.getExceptionCount() == 2); - // Test validly set property matches - assertTrue("Valid set property must stick", target.getName().equals(newName)); - assertTrue("Invalid set property must retain old value", target.getAge() == 0); - assertTrue("New value of dodgy setter must be available through exception", - ex.getPropertyAccessException("touchy").getPropertyChangeEvent().getNewValue().equals(invalidTouchy)); - } + BeanWrapper accessor = createAccessor(target); + MutablePropertyValues pvs = new MutablePropertyValues(); + pvs.addPropertyValue(new PropertyValue("age", "foobar")); + pvs.addPropertyValue(new PropertyValue("name", newName)); + pvs.addPropertyValue(new PropertyValue("touchy", invalidTouchy)); + assertThatExceptionOfType(PropertyBatchUpdateException.class).isThrownBy(() -> + accessor.setPropertyValues(pvs)) + .satisfies(ex -> { + assertThat(ex.getExceptionCount()).isEqualTo(2); + assertThat(ex.getPropertyAccessException("touchy").getPropertyChangeEvent() + .getNewValue()).isEqualTo(invalidTouchy); + }); + // Test validly set property matches + assertTrue("Valid set property must stick", target.getName().equals(newName)); + assertTrue("Invalid set property must retain old value", target.getAge() == 0); } @Test public void checkNotWritablePropertyHoldPossibleMatches() { TestBean target = new TestBean(); - try { - BeanWrapper accessor = createAccessor(target); - accessor.setPropertyValue("ag", "foobar"); - fail("Should throw exception on invalid property"); - } - catch (NotWritablePropertyException ex) { - // expected - assertEquals(1, ex.getPossibleMatches().length); - assertEquals("age", ex.getPossibleMatches()[0]); - } + BeanWrapper accessor = createAccessor(target); + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + accessor.setPropertyValue("ag", "foobar")) + .satisfies(ex -> assertThat(ex.getPossibleMatches()).containsExactly("age")); } @Test // Can't be shared; there is no such thing as a read-only field @@ -214,14 +206,10 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { @Test public void incompletelyQuotedKeyLeadsToPropertyException() { TestBean target = new TestBean(); - try { - BeanWrapper accessor = createAccessor(target); - accessor.setPropertyValue("[']", "foobar"); - fail("Should throw exception on invalid property"); - } - catch (NotWritablePropertyException ex) { - assertNull(ex.getPossibleMatches()); - } + BeanWrapper accessor = createAccessor(target); + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + accessor.setPropertyValue("[']", "foobar")) + .satisfies(ex -> assertThat(ex.getPossibleMatches()).isNull()); } diff --git a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java index 04f35b71dff..14244589ea5 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java @@ -30,7 +30,6 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Guillaume Poirier @@ -75,7 +74,7 @@ public class ConcurrentBeanWrapperTests { } } if (ex != null) { - fail(ex.getMessage()); + throw new AssertionError("Unexpected exception", ex); } } 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 0441b9f010b..0aae952562b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -33,7 +33,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Chris Beams @@ -176,7 +175,7 @@ public class ExtendedBeanInfoTests { return; } } - fail("never matched write method"); + throw new AssertionError("never matched write method"); } @Test @@ -671,7 +670,7 @@ public class ExtendedBeanInfoTests { return; } } - fail("never matched write method"); + throw new AssertionError("never matched write method"); } @Test @@ -699,7 +698,7 @@ public class ExtendedBeanInfoTests { return; } } - fail("never matched write method"); + throw new AssertionError("never matched write method"); } /** 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 7369b57aec5..9fc958495d7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java @@ -20,13 +20,13 @@ import java.util.Iterator; import org.junit.Test; +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; -import static org.junit.Assert.fail; /** * Tests for {@link MutablePropertyValues}. @@ -122,14 +122,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { PropertyValue pv = it.next(); assertEquals("foo", pv.getName()); assertEquals("bar", pv.getValue()); - - try { - it.remove(); - fail("Should have thrown UnsupportedOperationException"); - } - catch (UnsupportedOperationException ex) { - // expected - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(it::remove); assertFalse(it.hasNext()); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java index 3357aceb010..965d760922d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java @@ -37,7 +37,6 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -119,7 +118,7 @@ public class ConcurrentBeanFactoryTests { } } if (ex != null) { - fail(ex.getMessage()); + throw new AssertionError("Unexpected exception", ex); } } 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 9599904b648..54da9877340 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 @@ -99,7 +99,10 @@ import org.springframework.util.SerializationTestUtils; import org.springframework.util.StopWatch; import org.springframework.util.StringValueResolver; +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; @@ -110,7 +113,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -581,20 +583,14 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); Properties p = new Properties(); - try { - p.setProperty(PREFIX + "kerry.(class)", TestBean.class.getName()); - p.setProperty(PREFIX + "kerry.name", "Kerry"); - p.setProperty(PREFIX + "kerry.age", "35"); - p.setProperty(PREFIX + "kerry.spouse(ref)", "rod"); + p.setProperty(PREFIX + "kerry.(class)", TestBean.class.getName()); + p.setProperty(PREFIX + "kerry.name", "Kerry"); + p.setProperty(PREFIX + "kerry.age", "35"); + p.setProperty(PREFIX + "kerry.spouse(ref)", "rod"); - (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p, PREFIX); - - lbf.getBean("kerry"); - fail("Unresolved reference should have been detected"); - } - catch (BeansException ex) { - // cool - } + new PropertiesBeanDefinitionReader(lbf).registerBeanDefinitions(p, PREFIX); + assertThatExceptionOfType(BeansException.class).as("unresolved reference").isThrownBy(() -> + lbf.getBean("kerry")); } @Test @@ -611,23 +607,20 @@ public class DefaultListableBeanFactoryTests { @Test public void testPossibleMatches() { - try { - DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.add("ag", "foobar"); - RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); - bd.setPropertyValues(pvs); - lbf.registerBeanDefinition("tb", bd); - lbf.getBean("tb"); - fail("Should throw exception on invalid property"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof NotWritablePropertyException); - NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause(); - // expected - assertEquals(1, cause.getPossibleMatches().length); - assertEquals("age", cause.getPossibleMatches()[0]); - } + DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); + MutablePropertyValues pvs = new MutablePropertyValues(); + pvs.add("ag", "foobar"); + RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); + bd.setPropertyValues(pvs); + lbf.registerBeanDefinition("tb", bd); + assertThatExceptionOfType(BeanCreationException.class).as("invalid property").isThrownBy(() -> + lbf.getBean("tb")) + .withCauseInstanceOf(NotWritablePropertyException.class) + .satisfies(ex -> { + NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause(); + assertThat(cause.getPossibleMatches()).hasSize(1); + assertThat(cause.getPossibleMatches()[0]).isEqualTo("age"); + }); } @Test @@ -678,15 +671,10 @@ public class DefaultListableBeanFactoryTests { p.setProperty("rod.age", "34"); p.setProperty("rod.spouse", "*kerry"); - (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - try { - lbf.getBean("kerry"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.contains(BeanCurrentlyInCreationException.class)); - } + new PropertiesBeanDefinitionReader(lbf).registerBeanDefinitions(p); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + lbf.getBean("kerry")) + .satisfies(ex -> assertThat(ex.contains(BeanCurrentlyInCreationException.class)).isTrue()); } @Test @@ -804,23 +792,10 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.registerAlias("test", "test2"); lbf.registerAlias("test2", "test3"); - - try { - lbf.registerAlias("test3", "test2"); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - - try { - lbf.registerAlias("test3", "test"); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - + assertThatIllegalStateException().isThrownBy(() -> + lbf.registerAlias("test3", "test2")); + assertThatIllegalStateException().isThrownBy(() -> + lbf.registerAlias("test3", "test")); lbf.registerAlias("test", "test3"); } @@ -857,15 +832,13 @@ public class DefaultListableBeanFactoryTests { BeanDefinition oldDef = new RootBeanDefinition(TestBean.class); BeanDefinition newDef = new RootBeanDefinition(NestedTestBean.class); lbf.registerBeanDefinition("test", oldDef); - try { - lbf.registerBeanDefinition("test", newDef); - fail("Should have thrown BeanDefinitionOverrideException"); - } - catch (BeanDefinitionOverrideException ex) { - assertEquals("test", ex.getBeanName()); - assertSame(newDef, ex.getBeanDefinition()); - assertSame(oldDef, ex.getExistingDefinition()); - } + assertThatExceptionOfType(BeanDefinitionOverrideException.class).isThrownBy(() -> + lbf.registerBeanDefinition("test", newDef)) + .satisfies(ex -> { + assertThat(ex.getBeanName()).isEqualTo("test"); + assertThat(ex.getBeanDefinition()).isEqualTo(newDef); + assertThat(ex.getExistingDefinition()).isEqualTo(oldDef); + }); } @Test @@ -1123,13 +1096,8 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); Object singletonObject = new TestBean(); lbf.registerSingleton("singletonObject", singletonObject); - try { - lbf.registerSingleton("singletonObject", singletonObject); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + lbf.registerSingleton("singletonObject", singletonObject)); } @Test @@ -1301,15 +1269,10 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("rod", bd); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("rod2", bd2); - try { - lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertTrue(ex.getMessage().contains("rod")); - assertTrue(ex.getMessage().contains("rod2")); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false)) + .withMessageContaining("rod") + .withMessageContaining("rod2"); } @Test @@ -1321,13 +1284,8 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); assertEquals(1, lbf.getBeanDefinitionCount()); - try { - lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true); - fail("Should have unsatisfied constructor dependency on SideEffectBean"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true)); } @Test @@ -1359,13 +1317,8 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("spous", bd); - try { - lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true)); } @Test @@ -1387,16 +1340,11 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); bd2.setDependsOn("tb1"); lbf.registerBeanDefinition("tb2", bd2); - try { - lbf.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.getMessage().contains("Circular")); - assertTrue(ex.getMessage().contains("'tb2'")); - assertTrue(ex.getMessage().contains("'tb1'")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + lbf.preInstantiateSingletons()) + .withMessageContaining("Circular") + .withMessageContaining("'tb2'") + .withMessageContaining("'tb1'"); } @Test @@ -1411,22 +1359,18 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd3 = new RootBeanDefinition(TestBean.class); bd3.setDependsOn("tb1"); lbf.registerBeanDefinition("tb3", bd3); - try { - lbf.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.getMessage().contains("Circular")); - assertTrue(ex.getMessage().contains("'tb3'")); - assertTrue(ex.getMessage().contains("'tb1'")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + lbf::preInstantiateSingletons) + .withMessageContaining("Circular") + .withMessageContaining("'tb3'") + .withMessageContaining("'tb1'"); } - @Test(expected = NoSuchBeanDefinitionException.class) + @Test public void testGetBeanByTypeWithNoneFound() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - lbf.getBean(TestBean.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(TestBean.class)); } @Test @@ -1439,14 +1383,15 @@ public class DefaultListableBeanFactoryTests { assertThat(bean.getBeanName(), equalTo("bd1")); } - @Test(expected = NoUniqueBeanDefinitionException.class) + @Test public void testGetBeanByTypeWithAmbiguity() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd2", bd2); - lbf.getBean(TestBean.class); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(TestBean.class)); } @Test @@ -1581,49 +1526,22 @@ public class DefaultListableBeanFactoryTests { assertSame(lbf.getBean("bd1", TestBean.class), actual); lbf.registerBeanDefinition("bd2", bd2); - try { - lbf.getBean(TestBean.class); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(TestBean.class)); } @Test public void testGetBeanByTypeInstanceWithNoneFound() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - - try { - lbf.getBean(ConstructorDependency.class); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } - try { - lbf.getBean(ConstructorDependency.class, 42); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } - + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(ConstructorDependency.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(ConstructorDependency.class, 42)); ObjectProvider provider = lbf.getBeanProvider(ConstructorDependency.class); - try { - provider.getObject(); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } - try { - provider.getObject(42); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + provider::getObject); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + provider.getObject(42)); assertNull(provider.getIfAvailable()); assertNull(provider.getIfUnique()); } @@ -1666,44 +1584,17 @@ public class DefaultListableBeanFactoryTests { bd2.getConstructorArgumentValues().addGenericArgumentValue("43"); lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd2", bd2); - - try { - lbf.getBean(ConstructorDependency.class); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - try { - lbf.getBean(ConstructorDependency.class, 42); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(ConstructorDependency.class)); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(ConstructorDependency.class, 42)); ObjectProvider provider = lbf.getBeanProvider(ConstructorDependency.class); - try { - provider.getObject(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - try { - provider.getObject(42); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - try { - provider.getIfAvailable(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy( + provider::getObject); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> + provider.getObject(42)); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy( + provider::getIfAvailable); assertNull(provider.getIfUnique()); Set resolved = new HashSet<>(); @@ -1805,13 +1696,8 @@ public class DefaultListableBeanFactoryTests { assertThat(actual.beanName, equalTo("bd1")); lbf.registerBeanDefinition("bd2", bd2); - try { - lbf.getBean(TestBean.class, 67); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + lbf.getBean(TestBean.class, 67)); } @Test @@ -1822,20 +1708,10 @@ public class DefaultListableBeanFactoryTests { ObjectProvider provider = lbf.getBeanProvider(ConstructorDependency.class); ObjectProvider deserialized = (ObjectProvider) SerializationTestUtils.serializeAndDeserialize(provider); - try { - deserialized.getObject(); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } - try { - deserialized.getObject(42); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + deserialized::getObject); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + deserialized.getObject(42)); assertNull(deserialized.getIfAvailable()); assertNull(deserialized.getIfUnique()); } @@ -1976,14 +1852,15 @@ public class DefaultListableBeanFactoryTests { * Java method names. In other words, you can't name a method * {@code set&FactoryBean(...)}. */ - @Test(expected = TypeMismatchException.class) + @Test public void testAutowireBeanWithFactoryBeanByName() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class); lbf.registerBeanDefinition("factoryBean", bd); LazyInitFactory factoryBean = (LazyInitFactory) lbf.getBean("&factoryBean"); assertNotNull("The FactoryBean should have been registered.", factoryBean); - lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); + assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> + lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true)); } @Test @@ -1993,27 +1870,17 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); - try { - lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertTrue(ex.getMessage().contains("test")); - assertTrue(ex.getMessage().contains("spouse")); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true)) + .withMessageContaining("test") + .withMessageContaining("spouse"); } @Test public void testAutowireBeanByTypeWithDependencyCheck() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - try { - lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true)); } @Test @@ -2047,16 +1914,9 @@ public class DefaultListableBeanFactoryTests { bd2.setPrimary(true); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); - - try { - lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertNotNull("Exception should have cause", ex.getCause()); - assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true)) + .withCauseExactlyInstanceOf(NoUniqueBeanDefinitionException.class); } @Test @@ -2081,17 +1941,10 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd2 = new RootBeanDefinition(HighPriorityTestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); - - try { - lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertNotNull("Exception should have cause", ex.getCause()); - assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass()); - assertTrue(ex.getMessage().contains("5")); // conflicting priority - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true)) + .withCauseExactlyInstanceOf(NoUniqueBeanDefinitionException.class) + .withMessageContaining("5"); } @Test @@ -2127,13 +1980,8 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("spous", bd); DependenciesBean existingBean = new DependenciesBean(); - try { - lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true)); } @Test @@ -2161,12 +2009,8 @@ public class DefaultListableBeanFactoryTests { public void testAutowireExistingBeanByTypeWithDependencyCheck() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DependenciesBean existingBean = new DependenciesBean(); - try { - lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException expected) { - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true)); } @Test @@ -2180,12 +2024,8 @@ public class DefaultListableBeanFactoryTests { @Test public void testInvalidAutowireMode() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - try { - lbf.autowireBeanProperties(new TestBean(), AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + lbf.autowireBeanProperties(new TestBean(), AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false)); } @Test @@ -2292,12 +2132,8 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyBean.class); bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); lbf.registerBeanDefinition("test", bd); - try { - lbf.preInstantiateSingletons(); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException expected) { - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + lbf::preInstantiateSingletons); } @Test @@ -2306,12 +2142,8 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class); bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); lbf.registerBeanDefinition("test", bd); - try { - lbf.preInstantiateSingletons(); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException expected) { - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + lbf::preInstantiateSingletons); } @Test @@ -2320,12 +2152,8 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class); bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); lbf.registerBeanDefinition("test", bd); - try { - lbf.getBeansOfType(String.class); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException expected) { - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + lbf.getBeansOfType(String.class)); } @Test @@ -2355,41 +2183,28 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyWithClassResolution.class); bd.getConstructorArgumentValues().addGenericArgumentValue("java.lang.Strin"); lbf.registerBeanDefinition("test", bd); - try { - lbf.preInstantiateSingletons(); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException expected) { - assertTrue(expected.toString().contains("java.lang.Strin")); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + lbf::preInstantiateSingletons); } @Test public void testBeanDefinitionWithInterface() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.registerBeanDefinition("test", new RootBeanDefinition(ITestBean.class)); - try { - lbf.getBean("test"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertEquals("test", ex.getBeanName()); - assertTrue(ex.getMessage().toLowerCase().contains("interface")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + lbf.getBean("test")) + .withMessageContaining("interface") + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("test")); } @Test public void testBeanDefinitionWithAbstractClass() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.registerBeanDefinition("test", new RootBeanDefinition(AbstractBeanFactory.class)); - try { - lbf.getBean("test"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertEquals("test", ex.getBeanName()); - assertTrue(ex.getMessage().toLowerCase().contains("abstract")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + lbf.getBean("test")) + .withMessageContaining("abstract") + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("test")); } @Test @@ -2841,7 +2656,7 @@ public class DefaultListableBeanFactoryTests { assertEquals(expectedNameFromArgs, tb2.getName()); } - @Test(expected = IllegalStateException.class) + @Test public void testScopingBeanToUnregisteredScopeResultsInAnException() { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); @@ -2849,7 +2664,8 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("testBean", beanDefinition); - factory.getBean("testBean"); + assertThatIllegalStateException().isThrownBy(() -> + factory.getBean("testBean")); } @Test @@ -2915,9 +2731,7 @@ public class DefaultListableBeanFactoryTests { return !skipPropertyPopulation; } catch (Exception ex) { - fail("Unexpected exception: " + ex); - // Keep compiler happy about return - throw new IllegalStateException(); + throw new AssertionError("Unexpected exception", ex); } } }); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/Spr5475Tests.java b/spring-beans/src/test/java/org/springframework/beans/factory/Spr5475Tests.java index c614d28dd1a..eabc8c0a6f4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/Spr5475Tests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/Spr5475Tests.java @@ -23,9 +23,7 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; /** @@ -74,14 +72,9 @@ public class Spr5475Tests { private void assertExceptionMessageForMisconfiguredFactoryMethod(BeanDefinition bd, String expectedMessage) { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("foo", bd); - - try { - factory.preInstantiateSingletons(); - fail("should have failed with BeanCreationException due to incorrectly invoked factory method"); - } - catch (BeanCreationException ex) { - assertThat(ex.getMessage(), equalTo(expectedMessage)); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + factory::preInstantiateSingletons) + .withMessageContaining(expectedMessage); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java index 47f6b04e9ce..ff49dc6504c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java @@ -20,11 +20,11 @@ import org.junit.Test; import org.springframework.beans.factory.wiring.BeanWiringInfo; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * @author Rick Evans @@ -34,12 +34,8 @@ public class AnnotationBeanWiringInfoResolverTests { @Test public void testResolveWiringInfo() throws Exception { - try { - new AnnotationBeanWiringInfoResolver().resolveWiringInfo(null); - fail("Must have thrown an IllegalArgumentException by this point (null argument)"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new AnnotationBeanWiringInfoResolver().resolveWiringInfo(null)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java index d37911964d9..cf22c8a59a9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java @@ -36,6 +36,8 @@ import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; +import java.util.function.Consumer; +import java.util.function.Function; import java.util.stream.Collectors; import org.junit.After; @@ -49,6 +51,7 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; @@ -72,6 +75,8 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ReflectionUtils; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -80,7 +85,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -116,13 +120,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { @Test public void testIncompleteBeanDefinition() { bf.registerBeanDefinition("testBean", new GenericBeanDefinition()); - try { - bf.getBean("testBean"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getRootCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + bf.getBean("testBean")) + .withRootCauseInstanceOf(IllegalStateException.class); } @Test @@ -619,15 +619,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { @Test public void testConstructorResourceInjectionWithNoCandidatesAndNoFallback() { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorWithoutFallbackBean.class)); - - try { - bf.getBean("annotatedBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(ConstructorWithoutFallbackBean.class, ex.getInjectionPoint().getMethodParameter().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("annotatedBean")) + .satisfies(methodParameterDeclaredOn(ConstructorWithoutFallbackBean.class)); } @Test @@ -792,20 +786,21 @@ public class AutowiredAnnotationBeanPostProcessorTests { assertNull(bean.getNestedTestBeans()); } - @Test(expected = UnsatisfiedDependencyException.class) + @Test public void testSingleConstructorInjectionWithMissingDependency() { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SingleConstructorOptionalCollectionBean.class)); - bf.getBean("annotatedBean"); + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("annotatedBean")); } - @Test(expected = UnsatisfiedDependencyException.class) + @Test public void testSingleConstructorInjectionWithNullDependency() { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SingleConstructorOptionalCollectionBean.class)); RootBeanDefinition tb = new RootBeanDefinition(NullFactoryMethods.class); tb.setFactoryMethodName("createTestBean"); bf.registerBeanDefinition("testBean", tb); - - bf.getBean("annotatedBean"); + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("annotatedBean")); } @Test @@ -901,15 +896,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class)); bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); - - try { - bf.getBean("annotatedBean"); - fail("should have failed, more than one bean of type"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(MapMethodInjectionBean.class, ex.getInjectionPoint().getMethodParameter().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).as("should have failed, more than one bean of type").isThrownBy(() -> + bf.getBean("annotatedBean")) + .satisfies(methodParameterDeclaredOn(MapMethodInjectionBean.class)); } @Test @@ -1222,13 +1211,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectProviderInjectionBean.class)); ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); - try { - bean.getTestBean(); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + bean::getTestBean); assertNull(bean.getOptionalTestBean()); assertNull(bean.consumeOptionalTestBean()); assertEquals(new TestBean("default"), bean.getOptionalTestBeanWithDefault()); @@ -1253,27 +1237,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); - try { - bean.getTestBean(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - try { - bean.getOptionalTestBean(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - try { - bean.consumeOptionalTestBean(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getTestBean); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getOptionalTestBean); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::consumeOptionalTestBean); assertNull(bean.getUniqueTestBean()); assertNull(bean.consumeUniqueTestBean()); @@ -1374,16 +1340,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bpp.setRequiredParameterValue(false); bf.registerBeanDefinition("customBean", new RootBeanDefinition( CustomAnnotationRequiredFieldResourceInjectionBean.class)); - - try { - bf.getBean("customBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(CustomAnnotationRequiredFieldResourceInjectionBean.class, - ex.getInjectionPoint().getField().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("customBean")) + .satisfies(fieldDeclaredOn(CustomAnnotationRequiredFieldResourceInjectionBean.class)); } @Test @@ -1397,16 +1356,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean1", tb1); TestBean tb2 = new TestBean(); bf.registerSingleton("testBean2", tb2); - - try { - bf.getBean("customBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(CustomAnnotationRequiredFieldResourceInjectionBean.class, - ex.getInjectionPoint().getField().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("customBean")) + .satisfies(fieldDeclaredOn(CustomAnnotationRequiredFieldResourceInjectionBean.class)); } @Test @@ -1431,16 +1383,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bpp.setRequiredParameterValue(false); bf.registerBeanDefinition("customBean", new RootBeanDefinition( CustomAnnotationRequiredMethodResourceInjectionBean.class)); - - try { - bf.getBean("customBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(CustomAnnotationRequiredMethodResourceInjectionBean.class, - ex.getInjectionPoint().getMethodParameter().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("customBean")) + .satisfies(methodParameterDeclaredOn(CustomAnnotationRequiredMethodResourceInjectionBean.class)); } @Test @@ -1454,16 +1399,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean1", tb1); TestBean tb2 = new TestBean(); bf.registerSingleton("testBean2", tb2); - - try { - bf.getBean("customBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(CustomAnnotationRequiredMethodResourceInjectionBean.class, - ex.getInjectionPoint().getMethodParameter().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("customBean")) + .satisfies(methodParameterDeclaredOn(CustomAnnotationRequiredMethodResourceInjectionBean.class)); } @Test @@ -1509,16 +1447,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean1", tb1); TestBean tb2 = new TestBean(); bf.registerSingleton("testBean2", tb2); - - try { - bf.getBean("customBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(CustomAnnotationOptionalFieldResourceInjectionBean.class, - ex.getInjectionPoint().getField().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("customBean")) + .satisfies(fieldDeclaredOn(CustomAnnotationOptionalFieldResourceInjectionBean.class)); } @Test @@ -1564,16 +1495,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean1", tb1); TestBean tb2 = new TestBean(); bf.registerSingleton("testBean2", tb2); - - try { - bf.getBean("customBean"); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - assertSame(CustomAnnotationOptionalMethodResourceInjectionBean.class, - ex.getInjectionPoint().getMethodParameter().getDeclaringClass()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + bf.getBean("customBean")) + .satisfies(methodParameterDeclaredOn(CustomAnnotationOptionalMethodResourceInjectionBean.class)); } /** @@ -2219,6 +2143,30 @@ public class AutowiredAnnotationBeanPostProcessorTests { assertSame(bf.getBean("annotatedBean"), bean.testBean); } + private Consumer methodParameterDeclaredOn( + Class expected) { + return declaredOn( + injectionPoint -> injectionPoint.getMethodParameter().getDeclaringClass(), + expected); + } + + private Consumer fieldDeclaredOn( + Class expected) { + return declaredOn( + injectionPoint -> injectionPoint.getField().getDeclaringClass(), + expected); + } + + private Consumer declaredOn( + Function> declaringClassExtractor, + Class expected) { + return ex -> { + InjectionPoint injectionPoint = ex.getInjectionPoint(); + Class declaringClass = declaringClassExtractor.apply(injectionPoint); + assertThat(declaringClass).isSameAs(expected); + }; + } + @Qualifier("testBean") private void testBeanQualifierProvider() {} diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java index 3a979d635f0..cdfb07cf18b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java @@ -45,6 +45,7 @@ import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -52,7 +53,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor} @@ -313,14 +313,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class)); bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); - - try { - bf.getBean("annotatedBean"); - fail("should have failed, more than one bean of type"); - } - catch (BeanCreationException e) { - // expected - } + assertThatExceptionOfType(BeanCreationException.class).as("should have failed, more than one bean of type").isThrownBy(() -> + bf.getBean("annotatedBean")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java index 0dfb7ff288b..470e8a33d34 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java @@ -23,10 +23,10 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Karl Pietrzak @@ -95,12 +95,8 @@ public class LookupAnnotationTests { public void testWithThreeArgsShouldFail() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); assertNotNull(bean); - try { - bean.getThreeArguments("name", 1, 2); - fail("TestBean does not have a three arg constructor so this should not have worked"); - } - catch (AbstractMethodError ex) { - } + assertThatExceptionOfType(AbstractMethodError.class).as("TestBean has no three arg constructor").isThrownBy(() -> + bean.getThreeArguments("name", 1, 2)); assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java index 3c68ffbcfe8..530e9d51940 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java @@ -32,9 +32,8 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -46,48 +45,38 @@ public class RequiredAnnotationBeanPostProcessorTests { @Test public void testWithRequiredPropertyOmitted() { - try { - DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); - BeanDefinition beanDef = BeanDefinitionBuilder - .genericBeanDefinition(RequiredTestBean.class) - .addPropertyValue("name", "Rob Harrop") - .addPropertyValue("favouriteColour", "Blue") - .addPropertyValue("jobTitle", "Grand Poobah") - .getBeanDefinition(); - factory.registerBeanDefinition("testBean", beanDef); - factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); - factory.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - String message = ex.getCause().getMessage(); - assertTrue(message.contains("Property")); - assertTrue(message.contains("age")); - assertTrue(message.contains("testBean")); - } + DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); + BeanDefinition beanDef = BeanDefinitionBuilder + .genericBeanDefinition(RequiredTestBean.class) + .addPropertyValue("name", "Rob Harrop") + .addPropertyValue("favouriteColour", "Blue") + .addPropertyValue("jobTitle", "Grand Poobah") + .getBeanDefinition(); + factory.registerBeanDefinition("testBean", beanDef); + factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + factory::preInstantiateSingletons) + .withMessageContaining("Property") + .withMessageContaining("age") + .withMessageContaining("testBean"); } @Test public void testWithThreeRequiredPropertiesOmitted() { - try { - DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); - BeanDefinition beanDef = BeanDefinitionBuilder - .genericBeanDefinition(RequiredTestBean.class) - .addPropertyValue("name", "Rob Harrop") - .getBeanDefinition(); - factory.registerBeanDefinition("testBean", beanDef); - factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); - factory.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - String message = ex.getCause().getMessage(); - assertTrue(message.contains("Properties")); - assertTrue(message.contains("age")); - assertTrue(message.contains("favouriteColour")); - assertTrue(message.contains("jobTitle")); - assertTrue(message.contains("testBean")); - } + DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); + BeanDefinition beanDef = BeanDefinitionBuilder + .genericBeanDefinition(RequiredTestBean.class) + .addPropertyValue("name", "Rob Harrop") + .getBeanDefinition(); + factory.registerBeanDefinition("testBean", beanDef); + factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + factory::preInstantiateSingletons) + .withMessageContaining("Properties") + .withMessageContaining("age") + .withMessageContaining("favouriteColour") + .withMessageContaining("jobTitle") + .withMessageContaining("testBean"); } @Test @@ -109,48 +98,38 @@ public class RequiredAnnotationBeanPostProcessorTests { @Test public void testWithCustomAnnotation() { - try { - DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); - BeanDefinition beanDef = BeanDefinitionBuilder - .genericBeanDefinition(RequiredTestBean.class) - .getBeanDefinition(); - factory.registerBeanDefinition("testBean", beanDef); - RequiredAnnotationBeanPostProcessor rabpp = new RequiredAnnotationBeanPostProcessor(); - rabpp.setRequiredAnnotationType(MyRequired.class); - factory.addBeanPostProcessor(rabpp); - factory.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - String message = ex.getCause().getMessage(); - assertTrue(message.contains("Property")); - assertTrue(message.contains("name")); - assertTrue(message.contains("testBean")); - } + DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); + BeanDefinition beanDef = BeanDefinitionBuilder + .genericBeanDefinition(RequiredTestBean.class) + .getBeanDefinition(); + factory.registerBeanDefinition("testBean", beanDef); + RequiredAnnotationBeanPostProcessor rabpp = new RequiredAnnotationBeanPostProcessor(); + rabpp.setRequiredAnnotationType(MyRequired.class); + factory.addBeanPostProcessor(rabpp); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + factory::preInstantiateSingletons) + .withMessageContaining("Property") + .withMessageContaining("name") + .withMessageContaining("testBean"); } @Test public void testWithStaticFactoryMethod() { - try { - DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); - BeanDefinition beanDef = BeanDefinitionBuilder - .genericBeanDefinition(RequiredTestBean.class) - .setFactoryMethod("create") - .addPropertyValue("name", "Rob Harrop") - .addPropertyValue("favouriteColour", "Blue") - .addPropertyValue("jobTitle", "Grand Poobah") - .getBeanDefinition(); - factory.registerBeanDefinition("testBean", beanDef); - factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); - factory.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - String message = ex.getCause().getMessage(); - assertTrue(message.contains("Property")); - assertTrue(message.contains("age")); - assertTrue(message.contains("testBean")); - } + DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); + BeanDefinition beanDef = BeanDefinitionBuilder + .genericBeanDefinition(RequiredTestBean.class) + .setFactoryMethod("create") + .addPropertyValue("name", "Rob Harrop") + .addPropertyValue("favouriteColour", "Blue") + .addPropertyValue("jobTitle", "Grand Poobah") + .getBeanDefinition(); + factory.registerBeanDefinition("testBean", beanDef); + factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + factory::preInstantiateSingletons) + .withMessageContaining("Property") + .withMessageContaining("age") + .withMessageContaining("testBean"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java index 5900055d645..e6432922424 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java @@ -23,6 +23,8 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -77,32 +79,35 @@ public class CustomScopeConfigurerTests { assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhereScopeMapHasNullScopeValueInEntrySet() { Map scopes = new HashMap<>(); scopes.put(FOO_SCOPE, null); CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.setScopes(scopes); - figurer.postProcessBeanFactory(factory); + assertThatIllegalArgumentException().isThrownBy(() -> + figurer.postProcessBeanFactory(factory)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhereScopeMapHasNonScopeInstanceInEntrySet() { Map scopes = new HashMap<>(); scopes.put(FOO_SCOPE, this); // <-- not a valid value... CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.setScopes(scopes); - figurer.postProcessBeanFactory(factory); + assertThatIllegalArgumentException().isThrownBy(() -> + figurer.postProcessBeanFactory(factory)); } @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expected = ClassCastException.class) + @Test public void testWhereScopeMapHasNonStringTypedScopeNameInKeySet() { Map scopes = new HashMap(); scopes.put(this, new NoOpScope()); // <-- not a valid value (the key)... CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.setScopes(scopes); - figurer.postProcessBeanFactory(factory); + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + figurer.postProcessBeanFactory(factory)); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java index cf3c5d7e510..9e3012c49f4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java @@ -26,11 +26,12 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.beans.support.ArgumentConvertingMethodInvoker; import org.springframework.util.MethodInvoker; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link MethodInvokingFactoryBean} and {@link MethodInvokingBean}. @@ -48,71 +49,35 @@ public class MethodInvokingFactoryBeanTests { // assert that only static OR non static are set, but not both or none MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean(); - try { - mcfb.afterPropertiesSet(); - fail(validationError); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet); mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetObject(this); mcfb.setTargetMethod("whatever"); - try { - mcfb.afterPropertiesSet(); - fail(validationError); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet); // bogus static method mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("some.bogus.Method.name"); - try { - mcfb.afterPropertiesSet(); - fail(validationError); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet); // bogus static method mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("method1"); - try { - mcfb.afterPropertiesSet(); - fail(validationError); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet); // missing method mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetObject(this); - try { - mcfb.afterPropertiesSet(); - fail(validationError); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet); // bogus method mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetObject(this); mcfb.setTargetMethod("bogus"); - try { - mcfb.afterPropertiesSet(); - fail(validationError); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet); // static method TestClass1._staticField1 = 0; @@ -162,13 +127,7 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("supertypes"); mcfb.setArguments("1", new Object()); - try { - mcfb.afterPropertiesSet(); - fail("Should have thrown NoSuchMethodException"); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet); } @Test @@ -240,26 +199,17 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("supertypes"); mcfb.setArguments(new ArrayList<>(), new ArrayList(), "hello", "bogus"); - try { - mcfb.afterPropertiesSet(); - fail("Matched method with wrong number of args"); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).as( + "Matched method with wrong number of args").isThrownBy( + mcfb::afterPropertiesSet); mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("supertypes"); mcfb.setArguments(1, new Object()); - try { - mcfb.afterPropertiesSet(); - mcfb.getObject(); - fail("Should have failed on getObject with mismatched argument types"); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).as( + "Should have failed on getObject with mismatched argument types").isThrownBy( + mcfb::afterPropertiesSet); mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); @@ -272,13 +222,9 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("supertypes2"); mcfb.setArguments(new ArrayList<>(), new ArrayList(), new Object()); - try { - mcfb.afterPropertiesSet(); - fail("Matched method when shouldn't have matched"); - } - catch (NoSuchMethodException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMethodException.class).as( + "Matched method when shouldn't have matched").isThrownBy( + mcfb::afterPropertiesSet); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java index f90c2494a40..4b38fb7f108 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java @@ -29,10 +29,10 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.tests.TestResourceUtils.qualifiedResource; @@ -127,33 +127,27 @@ public class ObjectFactoryCreatingFactoryBeanTests { @Test public void testWhenTargetBeanNameIsNull() throws Exception { - try { - new ObjectFactoryCreatingFactoryBean().afterPropertiesSet(); - fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property not set."); - } - catch (IllegalArgumentException expected) {} + assertThatIllegalArgumentException().as( + "'targetBeanName' property not set").isThrownBy( + new ObjectFactoryCreatingFactoryBean()::afterPropertiesSet); } @Test public void testWhenTargetBeanNameIsEmptyString() throws Exception { - try { - ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean(); - factory.setTargetBeanName(""); - factory.afterPropertiesSet(); - fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property set to (invalid) empty string."); - } - catch (IllegalArgumentException expected) {} + ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean(); + factory.setTargetBeanName(""); + assertThatIllegalArgumentException().as( + "'targetBeanName' property set to (invalid) empty string").isThrownBy( + factory::afterPropertiesSet); } @Test public void testWhenTargetBeanNameIsWhitespacedString() throws Exception { - try { - ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean(); - factory.setTargetBeanName(" \t"); - factory.afterPropertiesSet(); - fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property set to (invalid) only-whitespace string."); - } - catch (IllegalArgumentException expected) {} + ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean(); + factory.setTargetBeanName(" \t"); + assertThatIllegalArgumentException().as( + "'targetBeanName' property set to (invalid) only-whitespace string").isThrownBy( + factory::afterPropertiesSet); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java index 60cb5a296e3..db55103f288 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java @@ -44,12 +44,12 @@ import org.springframework.tests.sample.beans.IndexedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.tests.TestResourceUtils.qualifiedResource; @@ -481,35 +481,21 @@ public class PropertyResourceConfigurerTests { public void testPropertyPlaceholderConfigurerWithUnresolvableSystemProperty() { factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class) .addPropertyValue("touchy", "${user.dir}").getBeanDefinition()); - PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_NEVER); - - try { - ppc.postProcessBeanFactory(factory); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - assertTrue(ex.getMessage().contains("user.dir")); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + ppc.postProcessBeanFactory(factory)) + .withMessageContaining("user.dir"); } @Test public void testPropertyPlaceholderConfigurerWithUnresolvablePlaceholder() { factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class) .addPropertyValue("name", "${ref}").getBeanDefinition()); - PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); - - try { - ppc.postProcessBeanFactory(factory); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - assertTrue(ex.getMessage().contains("ref")); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + ppc.postProcessBeanFactory(factory)) + .withMessageContaining("ref"); } @Test @@ -615,14 +601,8 @@ public class PropertyResourceConfigurerTests { props.setProperty("var", "${m}"); props.setProperty("m", "${var}"); ppc.setProperties(props); - - try { - ppc.postProcessBeanFactory(factory); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + ppc.postProcessBeanFactory(factory)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java index f4b39dee9c3..08795d599a1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java @@ -27,11 +27,12 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.NestedCheckedException; import org.springframework.core.NestedRuntimeException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; @@ -80,27 +81,12 @@ public class ServiceLocatorFactoryBeanTests { genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestService2Locator.class) .getBeanDefinition()); - - try { - TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory"); - factory.getTestService(); - fail("Must fail on more than one matching type"); - } - catch (NoSuchBeanDefinitionException ex) { /* expected */ } - - try { - TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory2"); - factory.getTestService(null); - fail("Must fail on more than one matching type"); - } - catch (NoSuchBeanDefinitionException ex) { /* expected */ } - - try { - TestService2Locator factory = (TestService2Locator) bf.getBean("factory3"); - factory.getTestService(); - fail("Must fail on no matching types"); - } - catch (NoSuchBeanDefinitionException ex) { /* expected */ } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("more than one matching type").isThrownBy(() -> + ((TestServiceLocator) bf.getBean("factory")).getTestService()); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("more than one matching type").isThrownBy(() -> + ((TestServiceLocator2) bf.getBean("factory2")).getTestService(null)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("no matching types").isThrownBy(() -> + ((TestService2Locator) bf.getBean("factory3")).getTestService()); } @Test @@ -122,31 +108,14 @@ public class ServiceLocatorFactoryBeanTests { .addPropertyValue("serviceLocatorInterface", TestService2Locator.class) .addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException3.class) .getBeanDefinition()); - - try { - TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory"); - factory.getTestService(); - fail("Must fail on more than one matching type"); - } - catch (CustomServiceLocatorException1 expected) { - assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException); - } - - try { - TestServiceLocator2 factory2 = (TestServiceLocator2) bf.getBean("factory2"); - factory2.getTestService(null); - fail("Must fail on more than one matching type"); - } - catch (CustomServiceLocatorException2 expected) { - assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException); - } - - try { - TestService2Locator factory3 = (TestService2Locator) bf.getBean("factory3"); - factory3.getTestService(); - fail("Must fail on no matching type"); - } - catch (CustomServiceLocatorException3 ex) { /* expected */ } + assertThatExceptionOfType(CustomServiceLocatorException1.class).as("more than one matching type").isThrownBy(() -> + ((TestServiceLocator) bf.getBean("factory")).getTestService()) + .withCauseInstanceOf(NoSuchBeanDefinitionException.class); + assertThatExceptionOfType(CustomServiceLocatorException2.class).as("more than one matching type").isThrownBy(() -> + ((TestServiceLocator2) bf.getBean("factory2")).getTestService(null)) + .withCauseInstanceOf(NoSuchBeanDefinitionException.class); + assertThatExceptionOfType(CustomServiceLocatorException3.class).as("no matching type").isThrownBy(() -> + ((TestService2Locator) bf.getBean("factory3")).getTestService()); } @Test @@ -165,11 +134,8 @@ public class ServiceLocatorFactoryBeanTests { // now test with explicit id testBean = factory.getTestService("testService"); // now verify failure on bad id - try { - factory.getTestService("bogusTestService"); - fail("Illegal operation allowed"); - } - catch (NoSuchBeanDefinitionException ex) { /* expected */ } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + factory.getTestService("bogusTestService")); } @Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory @@ -241,41 +207,46 @@ public class ServiceLocatorFactoryBeanTests { assertTrue(testBean4 instanceof ExtendedTestService); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNoServiceLocatorInterfaceSupplied() throws Exception { - new ServiceLocatorFactoryBean().afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + new ServiceLocatorFactoryBean()::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhenServiceLocatorInterfaceIsNotAnInterfaceType() throws Exception { ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean(); factory.setServiceLocatorInterface(getClass()); - factory.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + factory::afterPropertiesSet); // should throw, bad (non-interface-type) serviceLocator interface supplied } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhenServiceLocatorExceptionClassToExceptionTypeWithOnlyNoArgCtor() throws Exception { ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean(); - factory.setServiceLocatorExceptionClass(ExceptionClassWithOnlyZeroArgCtor.class); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setServiceLocatorExceptionClass(ExceptionClassWithOnlyZeroArgCtor.class)); // should throw, bad (invalid-Exception-type) serviceLocatorException class supplied } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void testWhenServiceLocatorExceptionClassIsNotAnExceptionSubclass() throws Exception { ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean(); - factory.setServiceLocatorExceptionClass((Class) getClass()); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setServiceLocatorExceptionClass((Class) getClass())); // should throw, bad (non-Exception-type) serviceLocatorException class supplied } - @Test(expected = UnsupportedOperationException.class) + @Test public void testWhenServiceLocatorMethodCalledWithTooManyParameters() throws Exception { ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean(); factory.setServiceLocatorInterface(ServiceLocatorInterfaceWithExtraNonCompliantMethod.class); factory.afterPropertiesSet(); ServiceLocatorInterfaceWithExtraNonCompliantMethod locator = (ServiceLocatorInterfaceWithExtraNonCompliantMethod) factory.getObject(); - locator.getTestService("not", "allowed"); //bad method (too many args, doesn't obey class contract) + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + locator.getTestService("not", "allowed")); //bad method (too many args, doesn't obey class contract) } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java index a0238806cbf..6646055f2a4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java @@ -28,6 +28,8 @@ import org.springframework.core.io.AbstractResource; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.FileSystemResource; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -49,10 +51,12 @@ public class YamlMapFactoryBeanTests { assertEquals(0, this.factory.getObject().size()); } - @Test(expected = IllegalStateException.class) + @Test public void testSetBarfOnResourceNotFound() { - this.factory.setResources(new FileSystemResource("non-exsitent-file.yml")); - assertEquals(0, this.factory.getObject().size()); + assertThatIllegalStateException().isThrownBy(() -> { + this.factory.setResources(new FileSystemResource("non-exsitent-file.yml")); + this.factory.getObject().size(); + }); } @Test @@ -118,10 +122,11 @@ public class YamlMapFactoryBeanTests { assertEquals(Integer.valueOf(3), sub.get("key1.key2")); } - @Test(expected = DuplicateKeyException.class) + @Test public void testDuplicateKey() { this.factory.setResources(new ByteArrayResource("mymap:\n foo: bar\nmymap:\n bar: foo".getBytes())); - this.factory.getObject().get("mymap"); + assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(() -> + this.factory.getObject().get("mymap")); } } 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 b64beac80c7..6eced27caae 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 @@ -76,20 +76,22 @@ public class YamlPropertiesFactoryBeanTests { assertThat(properties.getProperty("foo.bar"), equalTo("spam")); } - @Test(expected = DuplicateKeyException.class) + @Test public void testLoadResourcesWithInternalOverride() { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource( "foo: bar\nspam:\n foo: baz\nfoo: bucket".getBytes())); - factory.getObject(); + assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy( + factory::getObject); } - @Test(expected = DuplicateKeyException.class) + @Test public void testLoadResourcesWithNestedInternalOverride() { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource( "foo:\n bar: spam\n foo: baz\nbreak: it\nfoo: bucket".getBytes())); - factory.getObject(); + assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy( + factory::getObject); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ConstructorArgumentEntryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ConstructorArgumentEntryTests.java index f37fb375528..8f4129cd65e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ConstructorArgumentEntryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ConstructorArgumentEntryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 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. @@ -18,6 +18,8 @@ package org.springframework.beans.factory.parsing; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + /** * Unit tests for {@link ConstructorArgumentEntry}. * @@ -26,9 +28,10 @@ import org.junit.Test; */ public class ConstructorArgumentEntryTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorBailsOnNegativeCtorIndexArgument() { - new ConstructorArgumentEntry(-1); + assertThatIllegalArgumentException().isThrownBy(() -> + new ConstructorArgumentEntry(-1)); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java index 98f09377d70..fe4c134c903 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.springframework.core.io.DescriptiveResource; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; @@ -33,11 +34,12 @@ import static org.mockito.Mockito.verify; */ public class FailFastProblemReporterTests { - @Test(expected = BeanDefinitionParsingException.class) + @Test public void testError() throws Exception { FailFastProblemReporter reporter = new FailFastProblemReporter(); - reporter.error(new Problem("VGER", new Location(new DescriptiveResource("here")), - null, new IllegalArgumentException())); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> + reporter.error(new Problem("VGER", new Location(new DescriptiveResource("here")), + null, new IllegalArgumentException()))); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PropertyEntryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PropertyEntryTests.java index f4ce95c75f7..c31aeb5fe5d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PropertyEntryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PropertyEntryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 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. @@ -18,6 +18,8 @@ package org.springframework.beans.factory.parsing; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + /** * Unit tests for {@link PropertyEntry}. * @@ -26,19 +28,22 @@ import org.junit.Test; */ public class PropertyEntryTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorBailsOnNullPropertyNameArgument() throws Exception { - new PropertyEntry(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new PropertyEntry(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorBailsOnEmptyPropertyNameArgument() throws Exception { - new PropertyEntry(""); + assertThatIllegalArgumentException().isThrownBy(() -> + new PropertyEntry("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorBailsOnWhitespacedPropertyNameArgument() throws Exception { - new PropertyEntry("\t "); + assertThatIllegalArgumentException().isThrownBy(() -> + new PropertyEntry("\t ")); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java index b7a27ae8155..dce9655da4b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java @@ -56,13 +56,13 @@ import org.springframework.tests.sample.beans.GenericIntegerBean; import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -131,14 +131,12 @@ public class BeanFactoryGenericsTests { rbd.getPropertyValues().add("testBeanList", input); bf.registerBeanDefinition("genericBean", rbd); - try { - bf.getBean("genericBean"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("genericBean") && ex.getMessage().contains("testBeanList[0]")); - assertTrue(ex.getMessage().contains(TestBean.class.getName()) && ex.getMessage().contains("Integer")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + bf.getBean("genericBean")) + .withMessageContaining("genericBean") + .withMessageContaining("testBeanList[0]") + .withMessageContaining(TestBean.class.getName()) + .withMessageContaining("Integer"); } @Test @@ -883,20 +881,8 @@ public class BeanFactoryGenericsTests { ObjectProvider> numberStoreProvider = bf.getBeanProvider(ResolvableType.forClass(NumberStore.class)); ObjectProvider> doubleStoreProvider = bf.getBeanProvider(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class)); ObjectProvider> floatStoreProvider = bf.getBeanProvider(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class)); - try { - numberStoreProvider.getObject(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } - try { - numberStoreProvider.getIfAvailable(); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(numberStoreProvider::getObject); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(numberStoreProvider::getIfAvailable); assertNull(numberStoreProvider.getIfUnique()); assertSame(bf.getBean("store1"), doubleStoreProvider.getObject()); assertSame(bf.getBean("store1"), doubleStoreProvider.getIfAvailable()); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java index 5b4544b8035..ab6894f5179 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java @@ -23,10 +23,10 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Karl Pietrzak @@ -85,12 +85,8 @@ public class LookupMethodTests { public void testWithThreeArgsShouldFail() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); assertNotNull(bean); - try { - bean.getThreeArguments("name", 1, 2); - fail("TestBean does not have a three arg constructor so this should not have worked"); - } - catch (AbstractMethodError ex) { - } + assertThatExceptionOfType(AbstractMethodError.class).as("does not have a three arg constructor").isThrownBy(() -> + bean.getThreeArguments("name", 1, 2)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java index ff948516d54..83f194df125 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java @@ -20,6 +20,8 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -51,18 +53,20 @@ public class ManagedListTests { assertSame(child, child.merge(null)); } - @Test(expected = IllegalStateException.class) + @Test public void mergeNotAllowedWhenMergeNotEnabled() { ManagedList child = new ManagedList(); - child.merge(null); + assertThatIllegalStateException().isThrownBy(() -> + child.merge(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void mergeWithNonCompatibleParentType() { ManagedList child = new ManagedList(); child.add("one"); child.setMergeEnabled(true); - child.merge("hello"); + assertThatIllegalArgumentException().isThrownBy(() -> + child.merge("hello")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java index 7c70a0850fe..5aa657504fb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java @@ -20,6 +20,8 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -50,16 +52,18 @@ public class ManagedMapTests { assertSame(child, child.merge(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void mergeWithNonCompatibleParentType() { ManagedMap map = new ManagedMap(); map.setMergeEnabled(true); - map.merge("hello"); + assertThatIllegalArgumentException().isThrownBy(() -> + map.merge("hello")); } - @Test(expected = IllegalStateException.class) + @Test public void mergeNotAllowedWhenMergeNotEnabled() { - new ManagedMap().merge(null); + assertThatIllegalStateException().isThrownBy(() -> + new ManagedMap().merge(null)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java index 2079884b00c..fa792da09f0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java @@ -20,6 +20,8 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -50,17 +52,19 @@ public class ManagedPropertiesTests { assertSame(child, child.merge(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void mergeWithNonCompatibleParentType() { ManagedProperties map = new ManagedProperties(); map.setMergeEnabled(true); - map.merge("hello"); + assertThatIllegalArgumentException().isThrownBy(() -> + map.merge("hello")); } - @Test(expected = IllegalStateException.class) + @Test public void mergeNotAllowedWhenMergeNotEnabled() { ManagedProperties map = new ManagedProperties(); - map.merge(null); + assertThatIllegalStateException().isThrownBy(() -> + map.merge(null)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java index 8bf16dbb71d..41d17b7c51c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java @@ -20,6 +20,8 @@ import java.util.Set; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -51,17 +53,19 @@ public class ManagedSetTests { assertSame(child, child.merge(null)); } - @Test(expected = IllegalStateException.class) + @Test public void mergeNotAllowedWhenMergeNotEnabled() { - new ManagedSet().merge(null); + assertThatIllegalStateException().isThrownBy(() -> + new ManagedSet().merge(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void mergeWithNonCompatibleParentType() { ManagedSet child = new ManagedSet(); child.add("one"); child.setMergeEnabled(true); - child.merge("hello"); + assertThatIllegalArgumentException().isThrownBy(() -> + child.merge("hello")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java index 328210f5784..16aa897d1e7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java @@ -28,6 +28,7 @@ import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.util.PropertyPermission; import java.util.Set; +import java.util.function.Consumer; import javax.security.auth.AuthPermission; import javax.security.auth.Subject; @@ -50,14 +51,15 @@ import org.springframework.beans.factory.support.SecurityContextProvider; import org.springframework.beans.factory.support.security.support.ConstructorBean; import org.springframework.beans.factory.support.security.support.CustomCallbackBean; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.core.NestedRuntimeException; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Security test case. Checks whether the container uses its privileges for its @@ -325,68 +327,38 @@ public class CallbacksSecurityTests { @Test public void testSecuritySanity() throws Exception { AccessControlContext acc = provider.getAccessControlContext(); - try { - acc.checkPermission(new PropertyPermission("*", "read")); - fail("Acc should not have any permissions"); - } - catch (SecurityException se) { - // expected - } + assertThatExceptionOfType(SecurityException.class).as( + "Acc should not have any permissions").isThrownBy(() -> + acc.checkPermission(new PropertyPermission("*", "read"))); - final CustomCallbackBean bean = new CustomCallbackBean(); - final Method method = bean.getClass().getMethod("destroy"); + CustomCallbackBean bean = new CustomCallbackBean(); + Method method = bean.getClass().getMethod("destroy"); method.setAccessible(true); - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + method.invoke(bean); + return null; + }, acc)); - @Override - public Object run() throws Exception { - method.invoke(bean); - return null; - } - }, acc); - fail("expected security exception"); - } - catch (Exception ex) { - } - - final Class cl = ConstructorBean.class; - try { - AccessController.doPrivileged( - new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - return cl.newInstance(); - } - }, acc); - fail("expected security exception"); - } - catch (Exception ex) { - } + Class cl = ConstructorBean.class; + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + AccessController.doPrivileged((PrivilegedExceptionAction) () -> + cl.newInstance(), acc)); } @Test public void testSpringInitBean() throws Exception { - try { - beanFactory.getBean("spring-init"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof SecurityException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("spring-init")) + .withCauseInstanceOf(SecurityException.class); } @Test public void testCustomInitBean() throws Exception { - try { - beanFactory.getBean("custom-init"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof SecurityException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("custom-init")) + .withCauseInstanceOf(SecurityException.class); } @Test @@ -405,14 +377,9 @@ public class CallbacksSecurityTests { @Test public void testCustomFactoryObject() throws Exception { - try { - beanFactory.getBean("spring-factory"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof SecurityException); - } - + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("spring-factory")) + .withCauseInstanceOf(SecurityException.class); } @Test @@ -423,47 +390,30 @@ public class CallbacksSecurityTests { @Test public void testCustomStaticFactoryMethod() throws Exception { - try { - beanFactory.getBean("custom-static-factory-method"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMostSpecificCause() instanceof SecurityException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("custom-static-factory-method")) + .satisfies(ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(SecurityException.class)); } @Test public void testCustomInstanceFactoryMethod() throws Exception { - try { - beanFactory.getBean("custom-factory-method"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMostSpecificCause() instanceof SecurityException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("custom-factory-method")) + .satisfies(ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(SecurityException.class)); } @Test public void testTrustedFactoryMethod() throws Exception { - try { - beanFactory.getBean("privileged-static-factory-method"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMostSpecificCause() instanceof SecurityException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("privileged-static-factory-method")) + .satisfies(mostSpecificCauseOf(SecurityException.class)); } @Test public void testConstructor() throws Exception { - try { - beanFactory.getBean("constructor"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.getMostSpecificCause() instanceof SecurityException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("constructor")) + .satisfies(mostSpecificCauseOf(SecurityException.class)); } @Test @@ -483,14 +433,9 @@ public class CallbacksSecurityTests { @Test public void testPropertyInjection() throws Exception { - try { - beanFactory.getBean("property-injection"); - fail("expected security exception"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("security")); - } - + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean("property-injection")) + .withMessageContaining("security"); beanFactory.getBean("working-property-injection"); } @@ -558,4 +503,9 @@ public class CallbacksSecurityTests { }, provider.getAccessControlContext()); } + private Consumer mostSpecificCauseOf(Class type) { + return ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(type); + + } + } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java index 7f666d7f1d1..56aa6fa9329 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java @@ -23,6 +23,7 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.given; @@ -36,9 +37,10 @@ import static org.mockito.Mockito.verify; */ public class BeanConfigurerSupportTests { - @Test(expected = IllegalArgumentException.class) + @Test public void supplyIncompatibleBeanFactoryImplementation() throws Exception { - new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class)); + assertThatIllegalArgumentException().isThrownBy(() -> + new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class))); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java index e873a11d8d9..ee1b842d907 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java @@ -18,6 +18,7 @@ package org.springframework.beans.factory.wiring; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -29,29 +30,34 @@ import static org.junit.Assert.assertTrue; */ public class BeanWiringInfoTests { - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithNullBeanName() throws Exception { - new BeanWiringInfo(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new BeanWiringInfo(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithWhitespacedBeanName() throws Exception { - new BeanWiringInfo(" \t"); + assertThatIllegalArgumentException().isThrownBy(() -> + new BeanWiringInfo(" \t")); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithEmptyBeanName() throws Exception { - new BeanWiringInfo(""); + assertThatIllegalArgumentException().isThrownBy(() -> + new BeanWiringInfo("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithNegativeIllegalAutowiringValue() throws Exception { - new BeanWiringInfo(-1, true); + assertThatIllegalArgumentException().isThrownBy(() -> + new BeanWiringInfo(-1, true)); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithPositiveOutOfRangeAutowiringValue() throws Exception { - new BeanWiringInfo(123871, true); + assertThatIllegalArgumentException().isThrownBy(() -> + new BeanWiringInfo(123871, true)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java index ab0e11c615a..74b67760a3f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java @@ -18,6 +18,7 @@ package org.springframework.beans.factory.wiring; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -28,9 +29,10 @@ import static org.junit.Assert.assertNotNull; */ public class ClassNameBeanWiringInfoResolverTests { - @Test(expected = IllegalArgumentException.class) + @Test public void resolveWiringInfoWithNullBeanInstance() throws Exception { - new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java index ace2c223b5e..05aaec20522 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java @@ -34,11 +34,13 @@ import org.springframework.tests.sample.beans.MustBeInitialized; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Subclasses must initialize the bean factory and any other variables they need. @@ -67,9 +69,10 @@ public abstract class AbstractBeanFactoryTests { assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge()); } - @Test(expected = IllegalArgumentException.class) + @Test public void getBeanWithNullArg() { - getBeanFactory().getBean((String) null); + assertThatIllegalArgumentException().isThrownBy(() -> + getBeanFactory().getBean((String) null)); } /** @@ -114,17 +117,13 @@ public abstract class AbstractBeanFactoryTests { @Test public void getInstanceByNonmatchingClass() { - try { - getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass()); - } + assertThatExceptionOfType(BeanNotOfRequiredTypeException.class).isThrownBy(() -> + getBeanFactory().getBean("rod", BeanFactory.class)) + .satisfies(ex -> { + assertThat(ex.getBeanName()).isEqualTo("rod"); + assertThat(ex.getRequiredType()).isEqualTo(BeanFactory.class); + assertThat(ex.getActualType()).isEqualTo(TestBean.class).isEqualTo(getBeanFactory().getBean("rod").getClass()); + }); } @Test @@ -141,16 +140,13 @@ public abstract class AbstractBeanFactoryTests { @Test public void getSharedInstanceByNonmatchingClass() { - try { - getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - } + assertThatExceptionOfType(BeanNotOfRequiredTypeException.class).isThrownBy(() -> + getBeanFactory().getBean("rod", BeanFactory.class)) + .satisfies(ex -> { + assertThat(ex.getBeanName()).isEqualTo("rod"); + assertThat(ex.getRequiredType()).isEqualTo(BeanFactory.class); + assertThat(ex.getActualType()).isEqualTo(TestBean.class); + }); } @Test @@ -175,10 +171,11 @@ public abstract class AbstractBeanFactoryTests { assertTrue("object equal now false", !tb1.equals(tb2)); } - @Test(expected = BeansException.class) + @Test public void notThere() { assertFalse(getBeanFactory().containsBean("Mr Squiggle")); - getBeanFactory().getBean("Mr Squiggle"); + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + getBeanFactory().getBean("Mr Squiggle")); } @Test @@ -190,19 +187,16 @@ public abstract class AbstractBeanFactoryTests { } public void xtestTypeMismatch() { - try { - getBeanFactory().getBean("typeMismatch"); - fail("Shouldn't succeed with type mismatch"); - } - catch (BeanCreationException wex) { - assertEquals("typeMismatch", wex.getBeanName()); - assertTrue(wex.getCause() instanceof PropertyBatchUpdateException); - PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause(); - // Further tests - assertTrue("Has one error ", ex.getExceptionCount() == 1); - assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null); - assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + getBeanFactory().getBean("typeMismatch")) + .withCauseInstanceOf(PropertyBatchUpdateException.class) + .satisfies(ex -> { + assertThat(ex.getBeanName()).isEqualTo("typeMismatch"); + PropertyBatchUpdateException pex = (PropertyBatchUpdateException) ex.getCause(); + assertThat(pex.getExceptionCount()).isEqualTo(1); + assertThat(pex.getPropertyAccessException("age")).isNotNull(); + assertThat(pex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue()).isEqualTo("34x"); + }); } @Test @@ -256,9 +250,10 @@ public abstract class AbstractBeanFactoryTests { /** * It should be illegal to dereference a normal bean as a factory. */ - @Test(expected = BeanIsNotAFactoryException.class) + @Test public void rejectsFactoryGetOnNormalBean() { - getBeanFactory().getBean("&rod"); + assertThatExceptionOfType(BeanIsNotAFactoryException.class).isThrownBy(() -> + getBeanFactory().getBean("&rod")); } // TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory) @@ -272,14 +267,10 @@ public abstract class AbstractBeanFactoryTests { ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf; String alias = "rods alias"; - try { - cbf.getBean(alias); - fail("Shouldn't permit factory get on normal bean"); - } - catch (NoSuchBeanDefinitionException ex) { - // Ok - assertTrue(alias.equals(ex.getBeanName())); - } + + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + cbf.getBean(alias)) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo(alias)); // Create alias cbf.registerAlias("rod", alias); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DelegatingEntityResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DelegatingEntityResolverTests.java index 832a0645fb3..cb57798520b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DelegatingEntityResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DelegatingEntityResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 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,6 +20,8 @@ import org.junit.Test; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + /** * Unit tests for the {@link DelegatingEntityResolver} class. * @@ -28,19 +30,22 @@ import org.xml.sax.InputSource; */ public class DelegatingEntityResolverTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWhereDtdEntityResolverIsNull() throws Exception { - new DelegatingEntityResolver(null, new NoOpEntityResolver()); + assertThatIllegalArgumentException().isThrownBy(() -> + new DelegatingEntityResolver(null, new NoOpEntityResolver())); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWhereSchemaEntityResolverIsNull() throws Exception { - new DelegatingEntityResolver(new NoOpEntityResolver(), null); + assertThatIllegalArgumentException().isThrownBy(() -> + new DelegatingEntityResolver(new NoOpEntityResolver(), null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWhereEntityResolversAreBothNull() throws Exception { - new DelegatingEntityResolver(null, null); + assertThatIllegalArgumentException().isThrownBy(() -> + new DelegatingEntityResolver(null, null)); } 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 c74988091d4..1905a8893a5 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.assertThatExceptionOfType; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; /** * With Spring 3.1, bean id attributes (and all other id attributes across the @@ -46,13 +46,8 @@ public class DuplicateBeanIdTests { public void duplicateBeanIdsWithinSameNestingLevelRaisesError() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); - try { - reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass())); - fail("expected parsing exception due to duplicate ids in same nesting level"); - } - catch (Exception ex) { - // expected - } + assertThatExceptionOfType(Exception.class).as("duplicate ids in same nesting level").isThrownBy(() -> + reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass()))); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java index a542a2953e6..4fa9cf86d3d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java @@ -28,11 +28,11 @@ 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.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -79,14 +79,8 @@ public class FactoryMethodTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); - - try { - xbf.getBean("defaultTestBeanWithInvalidDestroyMethod"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("defaultTestBeanWithInvalidDestroyMethod")); } @Test @@ -96,14 +90,8 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); assertEquals("null", xbf.getBean("null").toString()); - - try { - xbf.getBean("nullWithProperty"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("nullWithProperty")); } @Test @@ -253,13 +241,8 @@ public class FactoryMethodTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); - try { - xbf.getBean("noMatchPrototype"); - fail("No static method matched"); - } - catch (BeanCreationException ex) { - // Ok - } + assertThatExceptionOfType(BeanCreationException.class).as("No static method matched").isThrownBy(() -> + xbf.getBean("noMatchPrototype")); } @Test @@ -267,13 +250,9 @@ public class FactoryMethodTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); - try { - xbf.getBean("invalidPrototype"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("nonExisting(TestBean)")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("invalidPrototype")) + .withMessageContaining("nonExisting(TestBean)"); } @Test @@ -281,13 +260,9 @@ public class FactoryMethodTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); - try { - xbf.getBean("invalidPrototype", new TestBean()); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("nonExisting(TestBean)")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("invalidPrototype", new TestBean())) + .withMessageContaining("nonExisting(TestBean)"); } @Test 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 23ce60ce114..32ff6616b9a 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 @@ -27,6 +27,7 @@ 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.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; @@ -62,9 +63,10 @@ public class ProfileXmlBeanDefinitionTests { private static final String TARGET_BEAN = "foo"; - @Test(expected = IllegalArgumentException.class) + @Test public void testProfileValidation() { - beanFactoryFor(PROD_ELIGIBLE_XML, NULL_ACTIVE); + assertThatIllegalArgumentException().isThrownBy(() -> + beanFactoryFor(PROD_ELIGIBLE_XML, NULL_ACTIVE)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java index 19db53f69aa..848ab75a8cc 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java @@ -24,10 +24,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.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -38,13 +37,9 @@ public class SchemaValidationTests { public void withAutodetection() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); - try { - reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass())); - fail("Should not be able to parse a file with errors"); - } - catch (BeansException ex) { - assertTrue(ex.getCause() instanceof SAXParseException); - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass()))) + .withCauseInstanceOf(SAXParseException.class); } @Test @@ -52,13 +47,9 @@ public class SchemaValidationTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); - try { - reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass())); - fail("Should not be able to parse a file with errors"); - } - catch (BeansException ex) { - assertTrue(ex.getCause() instanceof SAXParseException); - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass()))) + .withCauseInstanceOf(SAXParseException.class); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java index 5e854c97913..8a6505345d4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java @@ -24,6 +24,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.DummyBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -88,11 +89,12 @@ public class SimpleConstructorNamespaceHandlerTests { assertEquals(beanFactory.getBean("name-value"), typeRef.getSpouse()); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void ambiguousConstructor() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions( - new ClassPathResource("simpleConstructorNamespaceHandlerTestsWithErrors.xml", getClass())); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(bf).loadBeanDefinitions( + new ClassPathResource("simpleConstructorNamespaceHandlerTestsWithErrors.xml", getClass()))); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java index 15097de840d..09ae66a0f1d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java @@ -24,6 +24,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -57,11 +58,12 @@ public class SimplePropertyNamespaceHandlerTests { assertEquals(rob.getSpouse(), sally); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void withPropertyDefinedTwice() throws Exception { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( - new ClassPathResource("simplePropertyNamespaceHandlerTestsWithErrors.xml", getClass())); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( + new ClassPathResource("simplePropertyNamespaceHandlerTestsWithErrors.xml", getClass()))); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java index 87c66c2725b..7558679da3d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java @@ -42,10 +42,10 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.HasMap; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests for collections in XML bean definitions. @@ -178,14 +178,10 @@ public class XmlBeanCollectionTests { @Test public void testInvalidBeanNameReference() throws Exception { - try { - this.beanFactory.getBean("jumble2"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof BeanDefinitionStoreException); - assertTrue(ex.getCause().getMessage().contains("rod2")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + this.beanFactory.getBean("jumble2")) + .withCauseInstanceOf(BeanDefinitionStoreException.class) + .withMessageContaining("rod2"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java index 5f72c8abc03..e4d0e8eabfe 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java @@ -31,6 +31,7 @@ import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -48,11 +49,12 @@ public class XmlBeanDefinitionReaderTests { new XmlBeanDefinitionReader(registry).setDocumentReaderClass(DefaultBeanDefinitionDocumentReader.class); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void withOpenInputStream() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); Resource resource = new InputStreamResource(getClass().getResourceAsStream("test.xml")); - new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource)); } @Test @@ -81,11 +83,12 @@ public class XmlBeanDefinitionReaderTests { testBeanDefinitions(registry); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void withInputSource() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml")); - new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java index 32ed2408eda..746e9c0da35 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java @@ -22,9 +22,9 @@ import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver; import org.springframework.beans.factory.xml.NamespaceHandler; import org.springframework.beans.factory.xml.UtilNamespaceHandler; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * Unit and integration tests for the {@link DefaultNamespaceHandlerResolver} class. @@ -53,13 +53,7 @@ public class DefaultNamespaceHandlerResolverTests { @Test public void testNonExistentHandlerClass() { String mappingPath = "org/springframework/beans/factory/xml/support/nonExistent.properties"; - try { - new DefaultNamespaceHandlerResolver(getClass().getClassLoader(), mappingPath); - // pass - } - catch (Throwable ex) { - fail("Non-existent handler classes must be ignored: " + ex); - } + new DefaultNamespaceHandlerResolver(getClass().getClassLoader(), mappingPath); } @Test @@ -68,9 +62,10 @@ public class DefaultNamespaceHandlerResolverTests { new DefaultNamespaceHandlerResolver(null); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullClassLoaderArgumentAndNullMappingLocationArgument() { - new DefaultNamespaceHandlerResolver(null, null); + assertThatIllegalArgumentException().isThrownBy(() -> + new DefaultNamespaceHandlerResolver(null, null)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java index f0be94b62f8..fb83b6af35f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java @@ -22,6 +22,7 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -34,21 +35,24 @@ import static org.junit.Assert.assertTrue; */ public class CustomCollectionEditorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullCollectionType() throws Exception { - new CustomCollectionEditor(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomCollectionEditor(null)); } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCtorWithNonCollectionType() throws Exception { - new CustomCollectionEditor((Class) String.class); + assertThatIllegalArgumentException().isThrownBy(() -> + new CustomCollectionEditor((Class) String.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithCollectionTypeThatDoesNotExposeAPublicNoArgCtor() throws Exception { CustomCollectionEditor editor = new CustomCollectionEditor(CollectionTypeWithNoNoArgCtor.class); - editor.setValue("1"); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setValue("1")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java index f3b3c3bd8c9..1247bc9ea52 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java @@ -49,12 +49,14 @@ import org.springframework.tests.sample.beans.IndexedTestBean; import org.springframework.tests.sample.beans.NumberTestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for the various PropertyEditors in Spring. @@ -223,13 +225,8 @@ public class CustomEditorTests { bw.setPropertyValue("bool1", "0"); assertTrue("Correct bool1 value", !tb.isBool1()); - try { - bw.setPropertyValue("bool1", "argh"); - fail("Should have thrown BeansException"); - } - catch (BeansException ex) { - // expected - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + bw.setPropertyValue("bool1", "argh")); } @Test @@ -324,14 +321,8 @@ public class CustomEditorTests { editor.setAsText(falseString.toUpperCase()); assertFalse(((Boolean) editor.getValue()).booleanValue()); assertEquals(falseString, editor.getAsText()); - - try { - editor.setAsText(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(null)); } @Test @@ -453,16 +444,10 @@ public class CustomEditorTests { bw.setPropertyValue("long2", ""); assertTrue("Correct long2 value", bw.getPropertyValue("long2") == null); assertTrue("Correct long2 value", tb.getLong2() == null); - - try { - bw.setPropertyValue("long1", ""); - fail("Should have thrown BeansException"); - } - catch (BeansException ex) { - // expected - assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); - assertTrue("Correct long1 value", tb.getLong1() == 5); - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + bw.setPropertyValue("long1", "")); + assertThat(bw.getPropertyValue("long1")).isEqualTo(5L); + assertThat(tb.getLong1()).isEqualTo(5); } @Test @@ -481,14 +466,9 @@ public class CustomEditorTests { @Test public void testParseShortGreaterThanMaxValueWithoutNumberFormat() { - try { - CustomNumberEditor editor = new CustomNumberEditor(Short.class, true); - editor.setAsText(String.valueOf(Short.MAX_VALUE + 1)); - fail(Short.MAX_VALUE + 1 + " is greater than max value"); - } - catch (NumberFormatException ex) { - // expected - } + CustomNumberEditor editor = new CustomNumberEditor(Short.class, true); + assertThatExceptionOfType(NumberFormatException.class).as("greater than Short.MAX_VALUE + 1").isThrownBy(() -> + editor.setAsText(String.valueOf(Short.MAX_VALUE + 1))); } @Test @@ -551,10 +531,11 @@ public class CustomEditorTests { assertNull(cb.getMyCharacter()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); - charEditor.setAsText("ColdWaterCanyon"); + assertThatIllegalArgumentException().isThrownBy(() -> + charEditor.setAsText("ColdWaterCanyon")); } @Test @@ -570,10 +551,11 @@ public class CustomEditorTests { assertEquals(" ", charEditor.getAsText()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); - charEditor.setAsText(null); + assertThatIllegalArgumentException().isThrownBy(() -> + charEditor.setAsText(null)); } @Test @@ -591,10 +573,11 @@ public class CustomEditorTests { assertEquals("", classEditor.getAsText()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testClassEditorWithNonExistentClass() throws Exception { PropertyEditor classEditor = new ClassEditor(); - classEditor.setAsText("hairdresser.on.Fire"); + assertThatIllegalArgumentException().isThrownBy(() -> + classEditor.setAsText("hairdresser.on.Fire")); } @Test @@ -706,13 +689,8 @@ public class CustomEditorTests { assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); - try { - editor.setAsText(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(null)); } @Test @@ -758,22 +736,10 @@ public class CustomEditorTests { assertFalse(invalidDate.length() == maxLength); CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true, maxLength); - - try { - editor.setAsText(validDate); - } - catch (IllegalArgumentException ex) { - fail("Exception shouldn't be thrown because this is a valid date"); - } - - try { - editor.setAsText(invalidDate); - fail("Exception should be thrown because this is an invalid date"); - } - catch (IllegalArgumentException ex) { - // expected - assertTrue(ex.getMessage().contains("10")); - } + editor.setAsText(validDate); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(invalidDate)) + .withMessageContaining("10"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java index 9b544ba1164..bf1d16663db 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -44,10 +45,11 @@ public class FileEditorTests { assertTrue(file.exists()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNonExistentResource() throws Exception { PropertyEditor propertyEditor = new FileEditor(); - propertyEditor.setAsText("classpath:no_way_this_file_is_found.doc"); + assertThatIllegalArgumentException().isThrownBy(() -> + propertyEditor.setAsText("classpath:no_way_this_file_is_found.doc")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java index 4e8b7d944d9..e75b586940c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java @@ -22,6 +22,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -34,9 +35,10 @@ import static org.junit.Assert.assertTrue; */ public class InputStreamEditorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullResourceEditor() throws Exception { - new InputStreamEditor(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new InputStreamEditor(null)); } @Test @@ -60,10 +62,11 @@ public class InputStreamEditorTests { } } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhenResourceDoesNotExist() throws Exception { InputStreamEditor editor = new InputStreamEditor(); - editor.setAsText("classpath:bingo!"); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText("classpath:bingo!")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java index 2a89bf247cc..215f5a7e886 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java @@ -24,6 +24,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -44,10 +45,11 @@ public class PathEditorTests { assertTrue(path.toFile().exists()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNonExistentResource() throws Exception { PropertyEditor propertyEditor = new PathEditor(); - propertyEditor.setAsText("classpath:/no_way_this_file_is_found.doc"); + assertThatIllegalArgumentException().isThrownBy(() -> + propertyEditor.setAsText("classpath:/no_way_this_file_is_found.doc")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java index 767c6423225..353045b54f1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java @@ -22,6 +22,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -34,9 +35,10 @@ import static org.junit.Assert.assertTrue; */ public class ReaderEditorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullResourceEditor() throws Exception { - new ReaderEditor(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ReaderEditor(null)); } @Test @@ -60,11 +62,12 @@ public class ReaderEditorTests { } } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhenResourceDoesNotExist() throws Exception { String resource = "classpath:bingo!"; ReaderEditor editor = new ReaderEditor(); - editor.setAsText(resource); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(resource)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java index d402faa3a12..5a1d18cea8b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java @@ -20,6 +20,7 @@ import java.util.ResourceBundle; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -102,28 +103,32 @@ public class ResourceBundleEditorTests { assertEquals("ned", string); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetAsTextWithNull() throws Exception { ResourceBundleEditor editor = new ResourceBundleEditor(); - editor.setAsText(null); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetAsTextWithEmptyString() throws Exception { ResourceBundleEditor editor = new ResourceBundleEditor(); - editor.setAsText(""); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetAsTextWithWhiteSpaceString() throws Exception { ResourceBundleEditor editor = new ResourceBundleEditor(); - editor.setAsText(" "); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(" ")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetAsTextWithJustSeparatorString() throws Exception { ResourceBundleEditor editor = new ResourceBundleEditor(); - editor.setAsText("_"); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText("_")); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java index 5c97ed9eed2..e45cc287f2f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -33,9 +34,10 @@ import static org.junit.Assert.assertTrue; */ public class URLEditorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullResourceEditor() throws Exception { - new URLEditor(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new URLEditor(null)); } @Test @@ -70,10 +72,11 @@ public class URLEditorTests { assertTrue(!url.getProtocol().startsWith("classpath")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNonExistentResource() throws Exception { PropertyEditor urlEditor = new URLEditor(); - urlEditor.setAsText("gonna:/freak/in/the/morning/freak/in/the.evening"); + assertThatIllegalArgumentException().isThrownBy(() -> + urlEditor.setAsText("gonna:/freak/in/the/morning/freak/in/the.evening")); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java index ab6da01ff9a..01784f37766 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java @@ -29,11 +29,11 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -63,11 +63,11 @@ public class EhCacheSupportTests { @Test public void testCacheManagerConflict() { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); - cacheManagerFb.setCacheManagerName("myCacheManager"); - assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); - assertTrue("Singleton property", cacheManagerFb.isSingleton()); - cacheManagerFb.afterPropertiesSet(); try { + cacheManagerFb.setCacheManagerName("myCacheManager"); + assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); + assertTrue("Singleton property", cacheManagerFb.isSingleton()); + cacheManagerFb.afterPropertiesSet(); CacheManager cm = cacheManagerFb.getObject(); assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0); Cache myCache1 = cm.getCache("myCache1"); @@ -75,11 +75,8 @@ public class EhCacheSupportTests { EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean(); cacheManagerFb2.setCacheManagerName("myCacheManager"); - cacheManagerFb2.afterPropertiesSet(); - fail("Should have thrown CacheException because of naming conflict"); - } - catch (CacheException ex) { - // expected + assertThatExceptionOfType(CacheException.class).as("because of naming conflict").isThrownBy( + cacheManagerFb2::afterPropertiesSet); } finally { cacheManagerFb.destroy(); diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java index 67f577a659f..ecae1e83c7c 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java @@ -29,14 +29,16 @@ import org.springframework.cache.CacheManager; import org.springframework.cache.interceptor.SimpleKeyGenerator; import org.springframework.context.ApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIOException; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Stephane Nicoll @@ -99,13 +101,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); assertNull(cache.get(key)); - try { - service.cacheWithException(keyItem, true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.cacheWithException(keyItem, true)); Cache.ValueWrapper result = cache.get(key); assertNotNull(result); @@ -120,13 +117,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); assertNull(cache.get(key)); - try { - service.cacheWithException(keyItem, false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.cacheWithException(keyItem, false)); assertNull(cache.get(key)); } @@ -137,14 +129,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); assertNull(cache.get(key)); - - try { - service.cacheWithCheckedException(keyItem, true); - fail("Should have thrown an exception"); - } - catch (IOException e) { - // This is what we expect - } + assertThatIOException().isThrownBy(() -> + service.cacheWithCheckedException(keyItem, true)); Cache.ValueWrapper result = cache.get(key); assertNotNull(result); @@ -155,30 +141,26 @@ public abstract class AbstractJCacheAnnotationTests { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void cacheExceptionRewriteCallStack() { - final String keyItem = name.getMethodName(); - - UnsupportedOperationException first = null; + String keyItem = name.getMethodName(); long ref = service.exceptionInvocations(); - try { - service.cacheWithException(keyItem, true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - first = e; - } - // Sanity check, this particular call has called the service - assertEquals("First call should not have been cached", ref + 1, service.exceptionInvocations()); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.cacheWithException(keyItem, true)) + .satisfies(first -> { + // Sanity check, this particular call has called the service + // First call should not have been cached + assertThat(service.exceptionInvocations()).isEqualTo(ref + 1); - UnsupportedOperationException second = methodInCallStack(keyItem); - // Sanity check, this particular call has *not* called the service - assertEquals("Second call should have been cached", ref + 1, service.exceptionInvocations()); + UnsupportedOperationException second = methodInCallStack(keyItem); + // Sanity check, this particular call has *not* called the service + // Second call should have been cached + assertThat(service.exceptionInvocations()).isEqualTo(ref + 1); - assertEquals(first.getCause(), second.getCause()); - assertEquals(first.getMessage(), second.getMessage()); - assertFalse("Original stack must not contain any reference to methodInCallStack", - contain(first, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack")); - assertTrue("Cached stack should have been rewritten with a reference to methodInCallStack", - contain(second, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack")); + assertThat(first).hasCause(second.getCause()); + assertThat(first).hasMessage(second.getMessage()); + // Original stack must not contain any reference to methodInCallStack + assertThat(contain(first, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack")).isFalse(); + assertThat(contain(second, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack")).isTrue(); + }); } @Test @@ -246,13 +228,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); assertNull(cache.get(key)); - try { - service.putWithException(keyItem, value, true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.putWithException(keyItem, value, true)); Cache.ValueWrapper result = cache.get(key); assertNotNull(result); @@ -268,13 +245,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); assertNull(cache.get(key)); - try { - service.putWithException(keyItem, value, false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.putWithException(keyItem, value, false)); assertNull(cache.get(key)); } @@ -303,13 +275,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); assertNull(cache.get(key)); - try { - service.earlyPutWithException(keyItem, value, true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.earlyPutWithException(keyItem, value, true)); Cache.ValueWrapper result = cache.get(key); assertNotNull(result); @@ -324,14 +291,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); assertNull(cache.get(key)); - - try { - service.earlyPutWithException(keyItem, value, false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.earlyPutWithException(keyItem, value, false)); // This will be cached anyway as the earlyPut has updated the cache before Cache.ValueWrapper result = cache.get(key); assertNotNull(result); @@ -361,13 +322,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); cache.put(key, value); - try { - service.removeWithException(keyItem, true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.removeWithException(keyItem, true)); assertNull(cache.get(key)); } @@ -381,13 +337,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); cache.put(key, value); - try { - service.removeWithException(keyItem, false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.removeWithException(keyItem, false)); Cache.ValueWrapper wrapper = cache.get(key); assertNotNull(wrapper); assertEquals(value, wrapper.get()); @@ -416,13 +367,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); cache.put(key, value); - try { - service.earlyRemoveWithException(keyItem, true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.earlyRemoveWithException(keyItem, true)); assertNull(cache.get(key)); } @@ -435,13 +381,8 @@ public abstract class AbstractJCacheAnnotationTests { Object value = new Object(); cache.put(key, value); - try { - service.earlyRemoveWithException(keyItem, false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.earlyRemoveWithException(keyItem, false)); // This will be remove anyway as the earlyRemove has removed the cache before assertNull(cache.get(key)); } @@ -465,13 +406,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(name.getMethodName()); cache.put(key, new Object()); - try { - service.removeAllWithException(true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.removeAllWithException(true)); assertTrue(isEmpty(cache)); } @@ -483,13 +419,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(name.getMethodName()); cache.put(key, new Object()); - try { - service.removeAllWithException(false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.removeAllWithException(false)); assertNotNull(cache.get(key)); } @@ -512,13 +443,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(name.getMethodName()); cache.put(key, new Object()); - try { - service.earlyRemoveAllWithException(true); - fail("Should have thrown an exception"); - } - catch (UnsupportedOperationException e) { - // This is what we expect - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.earlyRemoveAllWithException(true)); assertTrue(isEmpty(cache)); } @@ -529,13 +455,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(name.getMethodName()); cache.put(key, new Object()); - try { - service.earlyRemoveAllWithException(false); - fail("Should have thrown an exception"); - } - catch (NullPointerException e) { - // This is what we expect - } + assertThatNullPointerException().isThrownBy(() -> + service.earlyRemoveAllWithException(false)); // This will be remove anyway as the earlyRemove has removed the cache before assertTrue(isEmpty(cache)); } diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java index 4ca058749ae..2853d1d227c 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java @@ -38,9 +38,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * @author Stephane Nicoll @@ -85,17 +84,9 @@ public class JCacheCustomInterceptorTests { @Test public void customInterceptorAppliesWithCheckedException() { - try { - cs.cacheWithCheckedException("id", true); - fail("Should have failed"); - } - catch (RuntimeException e) { - assertNotNull("missing original exception", e.getCause()); - assertEquals(IOException.class, e.getCause().getClass()); - } - catch (Exception e) { - fail("Wrong exception type " + e); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + cs.cacheWithCheckedException("id", true)) + .withCauseExactlyInstanceOf(IOException.class); } diff --git a/spring-context-support/src/test/java/org/springframework/mail/SimpleMailMessageTests.java b/spring-context-support/src/test/java/org/springframework/mail/SimpleMailMessageTests.java index 08eb0377323..0d786e27ca6 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/SimpleMailMessageTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/SimpleMailMessageTests.java @@ -22,6 +22,7 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -156,14 +157,16 @@ public class SimpleMailMessageTests { assertTrue(message1.equals(message2)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCopyCtorChokesOnNullOriginalMessage() throws Exception { - new SimpleMailMessage(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new SimpleMailMessage(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCopyToChokesOnNullTargetMessage() throws Exception { - new SimpleMailMessage().copyTo(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new SimpleMailMessage().copyTo(null)); } } diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java index 62c508763e3..95dec56c26c 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java @@ -18,6 +18,7 @@ package org.springframework.mail.javamail; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -69,9 +70,10 @@ public class InternetAddressEditorTests { assertEquals("Whitespace was not stripped", SIMPLE, editor.getAsText()); } - @Test(expected = IllegalArgumentException.class) + @Test public void simpleBadAddress() { - editor.setAsText(BAD); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText(BAD)); } } diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java index af242a40b62..16f43604f51 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java @@ -42,12 +42,12 @@ import org.springframework.mail.MailSendException; import org.springframework.mail.SimpleMailMessage; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.entry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -402,18 +402,9 @@ public class JavaMailSenderTests { sender.setUsername("username"); sender.setPassword("password"); SimpleMailMessage simpleMessage1 = new SimpleMailMessage(); - try { - sender.send(simpleMessage1); - fail("Should have thrown MailSendException"); - } - catch (MailSendException ex) { - // expected - ex.printStackTrace(); - assertTrue(ex.getFailedMessages() != null); - assertEquals(1, ex.getFailedMessages().size()); - assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next()); - assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next()); - } + assertThatExceptionOfType(MailSendException.class).isThrownBy(() -> + sender.send(simpleMessage1)) + .satisfies(ex -> assertThat(ex.getFailedMessages()).containsExactly(entry(simpleMessage1, (Exception) ex.getCause()))); } @Test @@ -423,16 +414,9 @@ public class JavaMailSenderTests { sender.setUsername("username"); sender.setPassword("password"); SimpleMailMessage simpleMessage1 = new SimpleMailMessage(); - try { - sender.send(simpleMessage1); - fail("Should have thrown MailSendException"); - } - catch (MailSendException ex) { - // expected - ex.printStackTrace(); - assertTrue(ex.getFailedMessages() != null); - assertEquals(0, ex.getFailedMessages().size()); - } + assertThatExceptionOfType(MailSendException.class).isThrownBy(() -> + sender.send(simpleMessage1)) + .satisfies(ex -> assertThat(ex.getFailedMessages()).isEmpty()); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java index f6d6763b8d8..9284ab0b1f3 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java @@ -41,6 +41,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; @@ -131,11 +132,12 @@ public class QuartzSupportTests { bean.destroy(); } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void jobDetailWithRunnableInsteadOfJob() { JobDetailImpl jobDetail = new JobDetailImpl(); - jobDetail.setJobClass((Class) DummyRunnable.class); + assertThatIllegalArgumentException().isThrownBy(() -> + jobDetail.setJobClass((Class) DummyRunnable.class)); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java index 31e382eebac..f39d102a3c1 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java @@ -29,9 +29,9 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.beanvalidation.BeanValidationPostProcessor; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -44,14 +44,9 @@ public class BeanValidationPostProcessorTests { ac.registerBeanDefinition("bvpp", new RootBeanDefinition(BeanValidationPostProcessor.class)); ac.registerBeanDefinition("capp", new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class)); ac.registerBeanDefinition("bean", new RootBeanDefinition(NotNullConstrainedBean.class)); - try { - ac.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getRootCause().getMessage().contains("testBean")); - assertTrue(ex.getRootCause().getMessage().contains("invalid")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + ac::refresh) + .satisfies(ex -> assertThat(ex.getRootCause().getMessage()).contains("testBean", "invalid")); ac.close(); } @@ -87,14 +82,9 @@ public class BeanValidationPostProcessorTests { bd.getPropertyValues().add("testBean", new TestBean()); bd.getPropertyValues().add("stringValue", "s"); ac.registerBeanDefinition("bean", bd); - try { - ac.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getRootCause().getMessage().contains("stringValue")); - assertTrue(ex.getRootCause().getMessage().contains("invalid")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + ac::refresh) + .satisfies(ex -> assertThat(ex.getRootCause().getMessage()).contains("stringValue", "invalid")); ac.close(); } diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java index 9d90f6a3469..5e7bd3dd5a7 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java @@ -18,6 +18,7 @@ package org.springframework.validation.beanvalidation2; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import javax.validation.ValidationException; import javax.validation.Validator; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; @@ -41,9 +42,9 @@ import org.springframework.validation.beanvalidation.CustomValidatorBean; import org.springframework.validation.beanvalidation.MethodValidationInterceptor; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -76,52 +77,20 @@ public class MethodValidationTests { private void doTestProxyValidation(MyValidInterface proxy) { assertNotNull(proxy.myValidMethod("value", 5)); - try { - assertNotNull(proxy.myValidMethod("value", 15)); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - try { - assertNotNull(proxy.myValidMethod(null, 5)); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - try { - assertNotNull(proxy.myValidMethod("value", 0)); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidMethod("value", 15)); + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidMethod(null, 5)); + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidMethod("value", 0)); proxy.myValidAsyncMethod("value", 5); - try { - proxy.myValidAsyncMethod("value", 15); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - try { - proxy.myValidAsyncMethod(null, 5); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidAsyncMethod("value", 15)); + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidAsyncMethod(null, 5)); assertEquals("myValue", proxy.myGenericMethod("myValue")); - try { - proxy.myGenericMethod(null); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myGenericMethod(null)); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java index 8bb478cc834..22309854959 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java @@ -52,13 +52,13 @@ import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +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; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -77,12 +77,8 @@ public class ValidatorFactoryTests { assertEquals(2, result.size()); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); - if ("name".equals(path) || "address.street".equals(path)) { - assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull); - } - else { - fail("Invalid constraint violation with path '" + path + "'"); - } + assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); + assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class); } Validator nativeValidator = validator.unwrap(Validator.class); @@ -105,12 +101,8 @@ public class ValidatorFactoryTests { assertEquals(2, result.size()); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); - if ("name".equals(path) || "address.street".equals(path)) { - assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull); - } - else { - fail("Invalid constraint violation with path '" + path + "'"); - } + assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); + assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class); } Validator nativeValidator = validator.unwrap(Validator.class); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java index 68dd4240981..29156c7425d 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java @@ -23,6 +23,7 @@ import org.springframework.aop.aspectj.AfterThrowingAdviceBindingTestAspect.Afte import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -54,44 +55,50 @@ public class AfterThrowingAdviceBindingTests { } - @Test(expected = Throwable.class) + @Test public void testSimpleAfterThrowing() throws Throwable { - this.testBean.exceptional(new Throwable()); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + this.testBean.exceptional(new Throwable())); verify(mockCollaborator).noArgs(); } - @Test(expected = Throwable.class) + @Test public void testAfterThrowingWithBinding() throws Throwable { Throwable t = new Throwable(); - this.testBean.exceptional(t); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + this.testBean.exceptional(t)); verify(mockCollaborator).oneThrowable(t); } - @Test(expected = Throwable.class) + @Test public void testAfterThrowingWithNamedTypeRestriction() throws Throwable { Throwable t = new Throwable(); - this.testBean.exceptional(t); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + this.testBean.exceptional(t)); verify(mockCollaborator).noArgs(); verify(mockCollaborator).oneThrowable(t); verify(mockCollaborator).noArgsOnThrowableMatch(); } - @Test(expected = Throwable.class) + @Test public void testAfterThrowingWithRuntimeExceptionBinding() throws Throwable { RuntimeException ex = new RuntimeException(); - this.testBean.exceptional(ex); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + this.testBean.exceptional(ex)); verify(mockCollaborator).oneRuntimeException(ex); } - @Test(expected = Throwable.class) + @Test public void testAfterThrowingWithTypeSpecified() throws Throwable { - this.testBean.exceptional(new Throwable()); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + this.testBean.exceptional(new Throwable())); verify(mockCollaborator).noArgsOnThrowableMatch(); } - @Test(expected = Throwable.class) + @Test public void testAfterThrowingWithRuntimeTypeSpecified() throws Throwable { - this.testBean.exceptional(new RuntimeException()); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + this.testBean.exceptional(new RuntimeException())); verify(mockCollaborator).noArgsOnRuntimeExceptionMatch(); } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java index cd28f10e80e..5cec4f6945a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java @@ -29,8 +29,6 @@ import org.springframework.core.Ordered; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.fail; - /** * @author Adrian Colyer * @author Chris Beams @@ -101,12 +99,12 @@ public class AspectAndAdvicePrecedenceTests { private void checkAdvice(String whatJustHappened) { //System.out.println("[" + adviceInvocationNumber + "] " + whatJustHappened + " ==> " + EXPECTED[adviceInvocationNumber]); if (adviceInvocationNumber > (EXPECTED.length - 1)) { - fail("Too many advice invocations, expecting " + EXPECTED.length + throw new AssertionError("Too many advice invocations, expecting " + EXPECTED.length + " but had " + adviceInvocationNumber); } String expecting = EXPECTED[adviceInvocationNumber++]; if (!whatJustHappened.equals(expecting)) { - fail("Expecting '" + expecting + "' on advice invocation " + adviceInvocationNumber + + throw new AssertionError("Expecting '" + expecting + "' on advice invocation " + adviceInvocationNumber + " but got '" + whatJustHappened + "'"); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java index ac890e670f3..015a2a87c21 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java @@ -24,9 +24,9 @@ import org.springframework.aop.support.AopUtils; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -69,13 +69,8 @@ public class DeclareParentsTests { testBeanProxy.setName(""); lockable.lock(); - try { - testBeanProxy.setName(" "); - fail("Should be locked"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().as("should be locked").isThrownBy(() -> + testBeanProxy.setName(" ")); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/spr3064/SPR3064Tests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/spr3064/SPR3064Tests.java index f2b795a094c..9aebe2488b9 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/spr3064/SPR3064Tests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/spr3064/SPR3064Tests.java @@ -26,8 +26,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Adrian Colyer @@ -44,14 +43,9 @@ public class SPR3064Tests { new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); service = (Service) ctx.getBean("service"); - - try { - this.service.serveMe(); - fail("service operation has not been advised by transaction interceptor"); - } - catch (RuntimeException ex) { - assertEquals("advice invoked",ex.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + this.service::serveMe) + .withMessageContaining("advice invoked"); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests.java index 1bb00244ec1..7ce4393893f 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests.java @@ -22,8 +22,7 @@ import org.xml.sax.SAXParseException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Adrian Colyer @@ -38,13 +37,9 @@ public class AopNamespaceHandlerAdviceTypeTests { @Test public void testParsingOfAdviceTypesWithError() { - try { - new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()); - fail("Expected BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - assertTrue(ex.contains(SAXParseException.class)); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass())) + .matches(ex -> ex.contains(SAXParseException.class)); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests.java index 31b23099459..bb1cfc0e7e4 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Adrian Colyer @@ -37,13 +36,9 @@ public class AopNamespaceHandlerArgNamesTests { @Test public void testArgNamesError() { - try { - new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()); - fail("Expected BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.contains(IllegalArgumentException.class)); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass())) + .matches(ex -> ex.contains(IllegalArgumentException.class)); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests.java index 785222d7265..1b78ec03c7b 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests.java @@ -22,8 +22,7 @@ import org.xml.sax.SAXParseException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Adrian Colyer @@ -38,13 +37,9 @@ public class AopNamespaceHandlerReturningTests { @Test public void testParseReturningOnOtherAdviceType() { - try { - new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()); - fail("Expected BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - assertTrue(ex.contains(SAXParseException.class)); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass())) + .matches(ex -> ex.contains(SAXParseException.class)); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests.java index 6c814abf64f..c7c016dad8f 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests.java @@ -22,8 +22,7 @@ import org.xml.sax.SAXParseException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Adrian Colyer @@ -38,13 +37,9 @@ public class AopNamespaceHandlerThrowingTests { @Test public void testParseThrowingOnOtherAdviceType() { - try { - new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()); - fail("Expected BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - assertTrue(ex.contains(SAXParseException.class)); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass())) + .matches(ex -> ex.contains(SAXParseException.class)); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java index ec340ccf095..f8c0fc5ac02 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -56,37 +57,42 @@ public class MethodLocatingFactoryBeanTests { assertEquals(Method.class, factory.getObjectType()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNullTargetBeanName() { factory.setMethodName("toString()"); - factory.setBeanFactory(beanFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setBeanFactory(beanFactory)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithEmptyTargetBeanName() { factory.setTargetBeanName(""); factory.setMethodName("toString()"); - factory.setBeanFactory(beanFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setBeanFactory(beanFactory)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNullTargetMethodName() { factory.setTargetBeanName(BEAN_NAME); - factory.setBeanFactory(beanFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setBeanFactory(beanFactory)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithEmptyTargetMethodName() { factory.setTargetBeanName(BEAN_NAME); factory.setMethodName(""); - factory.setBeanFactory(beanFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setBeanFactory(beanFactory)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWhenTargetBeanClassCannotBeResolved() { factory.setTargetBeanName(BEAN_NAME); factory.setMethodName("toString()"); - factory.setBeanFactory(beanFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setBeanFactory(beanFactory)); verify(beanFactory).getType(BEAN_NAME); } @@ -104,13 +110,14 @@ public class MethodLocatingFactoryBeanTests { assertEquals("Bingo", method.invoke("Bingo")); } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings("unchecked") public void testWhereMethodCannotBeResolved() { given(beanFactory.getType(BEAN_NAME)).willReturn((Class)String.class); factory.setTargetBeanName(BEAN_NAME); factory.setMethodName("loadOfOld()"); - factory.setBeanFactory(beanFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setBeanFactory(beanFactory)); } } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java index 8a4bfa07b10..1fb037c6986 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java @@ -76,6 +76,10 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; import org.springframework.util.StopWatch; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -83,7 +87,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -127,12 +130,14 @@ public abstract class AbstractAopProxyTests { } - @Test(expected = AopConfigException.class) + @Test public void testNoInterceptorsAndNoTarget() { - AdvisedSupport pc = new AdvisedSupport(ITestBean.class); - // Add no interceptors - AopProxy aop = createAopProxy(pc); - aop.getProxy(); + assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> { + AdvisedSupport pc = new AdvisedSupport(ITestBean.class); + //Add no interceptors + AopProxy aop = createAopProxy(pc); + aop.getProxy(); + }); } /** @@ -377,14 +382,15 @@ public abstract class AbstractAopProxyTests { assertEquals("3 more invocations via AOP as the first call was reentrant through the proxy", 4, di.getCount()); } - @Test(expected = IllegalStateException.class) + @Test // Should fail to get proxy as exposeProxy wasn't set to true public void testTargetCantGetProxyByDefault() { NeedsToSeeProxy et = new NeedsToSeeProxy(); ProxyFactory pf1 = new ProxyFactory(et); assertFalse(pf1.isExposeProxy()); INeedsToSeeProxy proxied = (INeedsToSeeProxy) createProxy(pf1); - proxied.incrementViaProxy(); + assertThatIllegalStateException().isThrownBy(() -> + proxied.incrementViaProxy()); } @Test @@ -468,15 +474,11 @@ public abstract class AbstractAopProxyTests { pc.setTargetSource(mockTargetSource); AopProxy aop = createAopProxy(pc); - try { - ITestBean tb = (ITestBean) aop.getProxy(); - // Note: exception param below isn't used - tb.exceptional(expectedException); - fail("Should have thrown exception raised by interceptor"); - } - catch (Exception thrown) { - assertEquals("exception matches", expectedException, thrown); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> { + ITestBean tb = (ITestBean) aop.getProxy(); + // Note: exception param below isn't used + tb.exceptional(expectedException); + }).matches(expectedException::equals); } /** @@ -503,18 +505,9 @@ public abstract class AbstractAopProxyTests { AopProxy aop = createAopProxy(pc); ITestBean tb = (ITestBean) aop.getProxy(); - try { - // Note: exception param below isn't used - tb.getAge(); - fail("Should have wrapped exception raised by interceptor"); - } - catch (UndeclaredThrowableException thrown) { - assertEquals("exception matches", unexpectedException, thrown.getUndeclaredThrowable()); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Didn't expect exception: " + ex); - } + assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy( + tb::getAge) + .satisfies(ex -> assertThat(ex.getUndeclaredThrowable()).isEqualTo(unexpectedException)); } @Test @@ -536,14 +529,9 @@ public abstract class AbstractAopProxyTests { AopProxy aop = createAopProxy(pc); ITestBean tb = (ITestBean) aop.getProxy(); - try { - // Note: exception param below isn't used - tb.getAge(); - fail("Should have wrapped exception raised by interceptor"); - } - catch (RuntimeException thrown) { - assertEquals("exception matches", unexpectedException, thrown); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + tb::getAge) + .matches(unexpectedException::equals); } /** @@ -591,13 +579,8 @@ public abstract class AbstractAopProxyTests { * Throw an exception if there is an Invocation. */ private void assertNoInvocationContext() { - try { - ExposeInvocationInterceptor.currentInvocation(); - fail("Expected no invocation context"); - } - catch (IllegalStateException ex) { - // ok - } + assertThatIllegalStateException().isThrownBy( + ExposeInvocationInterceptor::currentInvocation); } /** @@ -637,13 +620,8 @@ public abstract class AbstractAopProxyTests { lockable.lock(); assertEquals(newAge, itb.getAge()); - try { - itb.setAge(1); - fail("Setters should fail when locked"); - } - catch (LockedException ex) { - // ok - } + assertThatExceptionOfType(LockedException.class).isThrownBy(() -> + itb.setAge(1)); assertEquals(newAge, itb.getAge()); // Unlock @@ -737,13 +715,9 @@ public abstract class AbstractAopProxyTests { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); - try { - pc.addAdvice(new DummyIntroductionAdviceImpl()); - fail("Shouldn't be able to add introduction interceptor except via introduction advice"); - } - catch (AopConfigException ex) { - assertTrue(ex.getMessage().contains("ntroduction")); - } + assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> + pc.addAdvice(new DummyIntroductionAdviceImpl())) + .withMessageContaining("ntroduction"); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); assertEquals(target.getAge(), proxied.getAge()); @@ -755,18 +729,15 @@ public abstract class AbstractAopProxyTests { target.setAge(21); ProxyFactory pc = new ProxyFactory(target); pc.addAdvisor(new DefaultIntroductionAdvisor(new DummyIntroductionAdviceImpl(), Comparable.class)); - try { + assertThatExceptionOfType(Exception.class).isThrownBy(() -> { // TODO May fail on either call: may want to tighten up definition ITestBean proxied = (ITestBean) createProxy(pc); proxied.getName(); - fail("Bogus introduction"); - } - catch (Exception ex) { - // TODO used to catch UnknownAdviceTypeException, but - // with CGLIB some errors are in proxy creation and are wrapped - // in aspect exception. Error message is still fine. - //assertTrue(ex.getMessage().indexOf("ntroduction") > -1); - } + }); + // TODO used to catch UnknownAdviceTypeException, but + // with CGLIB some errors are in proxy creation and are wrapped + // in aspect exception. Error message is still fine. + //assertTrue(ex.getMessage().indexOf("ntroduction") > -1); } /** @@ -778,13 +749,8 @@ public abstract class AbstractAopProxyTests { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); - try { - pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), ITestBean.class)); - fail("Shouldn't be able to add introduction advice introducing an unimplemented interface"); - } - catch (IllegalArgumentException ex) { - //assertTrue(ex.getMessage().indexOf("ntroduction") > -1); - } + assertThatIllegalArgumentException().isThrownBy(() -> + pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), ITestBean.class))); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); assertEquals(target.getAge(), proxied.getAge()); @@ -813,12 +779,8 @@ public abstract class AbstractAopProxyTests { pc.addAdvisor(new DefaultIntroductionAdvisor(new MyDi())); TimeStamped ts = (TimeStamped) createProxy(pc); - try { - ts.getTimeStamp(); - fail("Should throw UnsupportedOperationException"); - } - catch (UnsupportedOperationException ex) { - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( + ts::getTimeStamp); } /** @@ -829,13 +791,9 @@ public abstract class AbstractAopProxyTests { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); - try { - pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), TestBean.class)); - fail("Shouldn't be able to add introduction advice that introduces a class, rather than an interface"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().contains("interface")); - } + assertThatIllegalArgumentException().as("Shouldn't be able to add introduction advice that introduces a class, rather than an interface").isThrownBy(() -> + pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), TestBean.class))) + .withMessageContaining("interface"); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); assertEquals(target.getAge(), proxied.getAge()); @@ -850,13 +808,9 @@ public abstract class AbstractAopProxyTests { pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); - try { - pc.addAdvice(0, new NopInterceptor()); - fail("Shouldn't be able to add interceptor when frozen"); - } - catch (AopConfigException ex) { - assertTrue(ex.getMessage().contains("frozen")); - } + assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add interceptor when frozen").isThrownBy(() -> + pc.addAdvice(0, new NopInterceptor())) + .withMessageContaining("frozen"); // Check it still works: proxy factory state shouldn't have been corrupted assertEquals(target.getAge(), proxied.getAge()); assertEquals(1, ((Advised) proxied).getAdvisors().length); @@ -877,13 +831,9 @@ public abstract class AbstractAopProxyTests { Advised advised = (Advised) proxied; assertTrue(pc.isFrozen()); - try { - advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor())); - fail("Shouldn't be able to add Advisor when frozen"); - } - catch (AopConfigException ex) { - assertTrue(ex.getMessage().contains("frozen")); - } + assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add Advisor when frozen").isThrownBy(() -> + advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()))) + .withMessageContaining("frozen"); // Check it still works: proxy factory state shouldn't have been corrupted assertEquals(target.getAge(), proxied.getAge()); assertEquals(1, advised.getAdvisors().length); @@ -901,13 +851,9 @@ public abstract class AbstractAopProxyTests { Advised advised = (Advised) proxied; assertTrue(pc.isFrozen()); - try { - advised.removeAdvisor(0); - fail("Shouldn't be able to remove Advisor when frozen"); - } - catch (AopConfigException ex) { - assertTrue(ex.getMessage().contains("frozen")); - } + assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to remove Advisor when frozen").isThrownBy(() -> + advised.removeAdvisor(0)) + .withMessageContaining("frozen"); // Didn't get removed assertEquals(1, advised.getAdvisors().length); pc.setFrozen(false); @@ -1424,13 +1370,8 @@ public abstract class AbstractAopProxyTests { assertEquals(2, cca.getCalls()); assertEquals(26, proxied.getAge()); assertEquals(4, cca.getCalls()); - try { - proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null)); - fail("Should have thrown CannotGetJdbcConnectionException"); - } - catch (SpecializedUncheckedException ex) { - // expected - } + assertThatExceptionOfType(SpecializedUncheckedException.class).as("Should have thrown CannotGetJdbcConnectionException").isThrownBy(() -> + proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null))); assertEquals(6, cca.getCalls()); } @@ -1463,13 +1404,9 @@ public abstract class AbstractAopProxyTests { assertEquals(1, nop1.getCount()); assertEquals(1, nop2.getCount()); // Will fail, after invoking Nop1 - try { - proxied.setAge(26); - fail("before advice should have ended chain"); - } - catch (RuntimeException ex) { - assertEquals(rex, ex); - } + assertThatExceptionOfType(RuntimeException.class).as("before advice should have ended chain").isThrownBy(() -> + proxied.setAge(26)) + .matches(rex::equals); assertEquals(2, ba.getCalls()); assertEquals(2, nop1.getCount()); // Nop2 didn't get invoked when the exception was thrown @@ -1532,13 +1469,9 @@ public abstract class AbstractAopProxyTests { assertEquals(2, car.getCalls()); Exception exc = new Exception(); // On exception it won't be invoked - try { - proxied.exceptional(exc); - fail(); - } - catch (Throwable t) { - assertSame(exc, t); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + proxied.exceptional(exc)) + .satisfies(ex -> assertThat(ex).isSameAs(exc)); assertEquals(2, car.getCalls()); } @@ -1567,22 +1500,13 @@ public abstract class AbstractAopProxyTests { assertEquals(0, th.getCalls()); Exception ex = new Exception(); // Will be advised but doesn't match - try { - proxied.echoException(1, ex); - fail(); - } - catch (Exception caught) { - assertEquals(ex, caught); - } - - ex = new FileNotFoundException(); - try { - proxied.echoException(1, ex); - fail(); - } - catch (FileNotFoundException caught) { - assertEquals(ex, caught); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + proxied.echoException(1, ex)) + .matches(ex::equals); + FileNotFoundException fex = new FileNotFoundException(); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + proxied.echoException(1, fex)) + .matches(fex::equals); assertEquals(1, th.getCalls("ioException")); } @@ -1602,23 +1526,16 @@ public abstract class AbstractAopProxyTests { assertEquals(0, th.getCalls()); Exception ex = new Exception(); // Will be advised but doesn't match - try { - proxied.echoException(1, ex); - fail(); - } - catch (Exception caught) { - assertEquals(ex, caught); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + proxied.echoException(1, ex)) + .matches(ex::equals); // Subclass of RemoteException - ex = new MarshalException(""); - try { - proxied.echoException(1, ex); - fail(); - } - catch (MarshalException caught) { - assertEquals(ex, caught); - } + MarshalException mex = new MarshalException(""); + assertThatExceptionOfType(MarshalException.class).isThrownBy(() -> + proxied.echoException(1, mex)) + .matches(mex::equals); + assertEquals(1, th.getCalls("remoteException")); } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java index fa9a1d60fab..12e62416da1 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java @@ -36,6 +36,8 @@ import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @@ -79,17 +81,19 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullConfig() { - new CglibAopProxy(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new CglibAopProxy(null)); } - @Test(expected = AopConfigException.class) + @Test public void testNoTarget() { AdvisedSupport pc = new AdvisedSupport(ITestBean.class); pc.addAdvice(new NopInterceptor()); AopProxy aop = createAopProxy(pc); - aop.getProxy(); + assertThatExceptionOfType(AopConfigException.class).isThrownBy( + aop::getProxy); } @Test diff --git a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java index 5440cc2c7ae..1d4a75f2f61 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java @@ -28,6 +28,7 @@ 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.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -56,9 +57,10 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullConfig() { - new JdkDynamicAopProxy(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new JdkDynamicAopProxy(null)); } @Test diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java index 586af2729eb..d86df4ba3ab 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java @@ -17,7 +17,6 @@ package org.springframework.aop.framework; import java.io.FileNotFoundException; -import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.LinkedList; @@ -61,6 +60,9 @@ import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIOException; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; @@ -70,7 +72,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @since 13.03.2003 @@ -144,32 +145,22 @@ public class ProxyFactoryBeanTests { } private void testDoubleTargetSourceIsRejected(String name) { - try { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(DBL_TARGETSOURCE_CONTEXT, CLASS)); - bf.getBean(name); - fail("Should not allow TargetSource to be specified in interceptorNames as well as targetSource property"); - } - catch (BeanCreationException ex) { - // Root cause of the problem must be an AOP exception - AopConfigException aex = (AopConfigException) ex.getCause(); - assertTrue(aex.getMessage().contains("TargetSource")); - } + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(DBL_TARGETSOURCE_CONTEXT, CLASS)); + assertThatExceptionOfType(BeanCreationException.class).as("Should not allow TargetSource to be specified in interceptorNames as well as targetSource property").isThrownBy(() -> + bf.getBean(name)) + .withCauseInstanceOf(AopConfigException.class) + .satisfies(ex -> assertThat(ex.getCause().getMessage()).contains("TargetSource")); } @Test public void testTargetSourceNotAtEndOfInterceptorNamesIsRejected() { - try { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(NOTLAST_TARGETSOURCE_CONTEXT, CLASS)); - bf.getBean("targetSourceNotLast"); - fail("TargetSource or non-advised object must be last in interceptorNames"); - } - catch (BeanCreationException ex) { - // Root cause of the problem must be an AOP exception - AopConfigException aex = (AopConfigException) ex.getCause(); - assertTrue(aex.getMessage().contains("interceptorNames")); - } + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(NOTLAST_TARGETSOURCE_CONTEXT, CLASS)); + assertThatExceptionOfType(BeanCreationException.class).as("TargetSource or non-advised object must be last in interceptorNames").isThrownBy(() -> + bf.getBean("targetSourceNotLast")) + .withCauseInstanceOf(AopConfigException.class) + .satisfies(ex -> assertThat(ex.getCause().getMessage()).contains("interceptorNames")); } @Test @@ -205,13 +196,9 @@ public class ProxyFactoryBeanTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(TARGETSOURCE_CONTEXT, CLASS)); ITestBean tb = (ITestBean) bf.getBean("noTarget"); - try { - tb.getName(); - fail(); - } - catch (UnsupportedOperationException ex) { - assertEquals("getName", ex.getMessage()); - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + tb.getName()) + .withMessage("getName"); FactoryBean pfb = (ProxyFactoryBean) bf.getBean("&noTarget"); assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(pfb.getObjectType())); } @@ -332,15 +319,10 @@ public class ProxyFactoryBeanTests { }); assertEquals("Have correct advisor count", 2, config.getAdvisors().length); - tb = (ITestBean) factory.getBean("test1"); - try { - // Will fail now - tb.toString(); - fail("Evil interceptor added programmatically should fail all method calls"); - } - catch (Exception thrown) { - assertTrue(thrown == ex); - } + ITestBean tb1 = (ITestBean) factory.getBean("test1"); + assertThatExceptionOfType(Exception.class).isThrownBy( + tb1::toString) + .satisfies(thrown -> assertThat(thrown).isSameAs(ex)); } /** @@ -466,25 +448,18 @@ public class ProxyFactoryBeanTests { assertEquals(2, cba.getCalls()); assertEquals(0, th.getCalls()); Exception expected = new Exception(); - try { - echo.echoException(1, expected); - fail(); - } - catch (Exception ex) { - assertEquals(expected, ex); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + echo.echoException(1, expected)) + .matches(expected::equals); // No throws handler method: count should still be 0 assertEquals(0, th.getCalls()); // Handler knows how to handle this exception - expected = new FileNotFoundException(); - try { - echo.echoException(1, expected); - fail(); - } - catch (IOException ex) { - assertEquals(expected, ex); - } + FileNotFoundException expectedFileNotFound = new FileNotFoundException(); + assertThatIOException().isThrownBy(() -> + echo.echoException(1, expectedFileNotFound)) + .matches(expectedFileNotFound::equals); + // One match assertEquals(1, th.getCalls("ioException")); } @@ -494,13 +469,8 @@ public class ProxyFactoryBeanTests { /* @Test public void testNoInterceptorNamesWithoutTarget() { - try { - ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget"); - fail("Should require interceptor names"); - } - catch (AopConfigException ex) { - // Ok - } + assertThatExceptionOfType(AopConfigurationException.class).as("Should require interceptor names").isThrownBy(() -> + ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget")); } @Test @@ -513,13 +483,8 @@ public class ProxyFactoryBeanTests { public void testEmptyInterceptorNames() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(INVALID_CONTEXT, CLASS)); - try { - bf.getBean("emptyInterceptorNames"); - fail("Interceptor names cannot be empty"); - } - catch (BeanCreationException ex) { - // Ok - } + assertThatExceptionOfType(BeanCreationException.class).as("Interceptor names cannot be empty").isThrownBy(() -> + bf.getBean("emptyInterceptorNames")); } /** @@ -529,13 +494,9 @@ public class ProxyFactoryBeanTests { public void testGlobalsWithoutTarget() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(INVALID_CONTEXT, CLASS)); - try { - bf.getBean("globalsWithoutTarget"); - fail("Should require target name"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof AopConfigException); - } + assertThatExceptionOfType(BeanCreationException.class).as("Should require target name").isThrownBy(() -> + bf.getBean("globalsWithoutTarget")) + .withCauseInstanceOf(AopConfigException.class); } /** @@ -559,12 +520,8 @@ public class ProxyFactoryBeanTests { agi = (AddedGlobalInterface) l; assertTrue(agi.globalsAdded() == -1); - try { - agi = (AddedGlobalInterface) factory.getBean("test1"); - fail("Aspect interface should't be implemeneted without globals"); - } - catch (ClassCastException ex) { - } + assertThat(factory.getBean("test1")).as("Aspect interface should't be implemeneted without globals") + .isNotInstanceOf(AddedGlobalInterface.class); } @Test @@ -639,20 +596,10 @@ public class ProxyFactoryBeanTests { ((Lockable) bean1).lock(); - try { - bean1.setAge(5); - fail("expected LockedException"); - } - catch (LockedException ex) { - // expected - } + assertThatExceptionOfType(LockedException.class).isThrownBy(() -> + bean1.setAge(5)); - try { - bean2.setAge(6); - } - catch (LockedException ex) { - fail("did not expect LockedException"); - } + bean2.setAge(6); //do not expect LockedException" } @Test @@ -670,20 +617,11 @@ public class ProxyFactoryBeanTests { ((Lockable) bean1).lock(); - try { - bean1.setAge(5); - fail("expected LockedException"); - } - catch (LockedException ex) { - // expected - } + assertThatExceptionOfType(LockedException.class).isThrownBy(() -> + bean1.setAge(5)); - try { - bean2.setAge(6); - } - catch (LockedException ex) { - fail("did not expect LockedException"); - } + // do not expect LockedException + bean2.setAge(6); } /** diff --git a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java index 288ef14c628..47a777fc433 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java @@ -31,8 +31,8 @@ import org.springframework.aop.framework.Advised; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * TestCase for AdvisorAdapterRegistrationManager mechanism. @@ -54,14 +54,9 @@ public class AdvisorAdapterRegistrationTests { new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-without-bpp.xml", getClass()); ITestBean tb = (ITestBean) ctx.getBean("testBean"); // just invoke any method to see if advice fired - try { - tb.getName(); - fail("Should throw UnknownAdviceTypeException"); - } - catch (UnknownAdviceTypeException ex) { - // expected - assertEquals(0, getAdviceImpl(tb).getInvocationCounter()); - } + assertThatExceptionOfType(UnknownAdviceTypeException.class).isThrownBy( + tb::getName); + assertThat(getAdviceImpl(tb).getInvocationCounter()).isZero(); } @Test @@ -70,13 +65,8 @@ public class AdvisorAdapterRegistrationTests { new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-with-bpp.xml", getClass()); ITestBean tb = (ITestBean) ctx.getBean("testBean"); // just invoke any method to see if advice fired - try { - tb.getName(); - assertEquals(1, getAdviceImpl(tb).getInvocationCounter()); - } - catch (UnknownAdviceTypeException ex) { - fail("Should not throw UnknownAdviceTypeException"); - } + tb.getName(); + getAdviceImpl(tb).getInvocationCounter(); } private SimpleBeforeAdviceImpl getAdviceImpl(ITestBean tb) { diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java index fb3b2cf4d43..02d183b6e63 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java @@ -25,6 +25,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -34,14 +35,15 @@ import static org.junit.Assert.assertEquals; */ public class BeanNameAutoProxyCreatorInitTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testIgnoreAdvisorThatIsCurrentlyInCreation() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass()); TestBean bean = (TestBean) ctx.getBean("bean"); bean.setName("foo"); assertEquals("foo", bean.getName()); - bean.setName(null); // should throw + assertThatIllegalArgumentException().isThrownBy(() -> + bean.setName(null)); } } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java index e9c3c71cfac..e33279c4cf7 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java @@ -32,10 +32,10 @@ import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -106,13 +106,8 @@ public class BeanNameAutoProxyCreatorTests { // Can still mod second object tb2.setAge(12); // But can't mod first - try { - tb.setAge(6); - fail("Mixin should have locked this object"); - } - catch (LockedException ex) { - // Ok - } + assertThatExceptionOfType(LockedException.class).as("mixin should have locked this object").isThrownBy(() -> + tb.setAge(6)); } @Test @@ -144,13 +139,8 @@ public class BeanNameAutoProxyCreatorTests { // Can still mod second object tb2.setAge(12); // But can't mod first - try { - tb.setAge(6); - fail("Mixin should have locked this object"); - } - catch (LockedException ex) { - // Ok - } + assertThatExceptionOfType(LockedException.class).as("mixin should have locked this object").isThrownBy(() -> + tb.setAge(6)); } @Test diff --git a/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java b/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java index 8faa9ad21e0..a8051de1018 100644 --- a/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java @@ -32,10 +32,10 @@ import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests for pooling invoker interceptor. @@ -151,13 +151,8 @@ public class CommonsPool2TargetSourceTests { } // should be at maximum now - try { - targetSource.getTarget(); - fail("Should throw NoSuchElementException"); - } - catch (NoSuchElementException ex) { - // desired - } + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( + targetSource::getTarget); // lets now release an object and try to acquire a new one targetSource.releaseTarget(pooledInstances[9]); @@ -184,13 +179,8 @@ public class CommonsPool2TargetSourceTests { } // should be at maximum now - try { - targetSource.getTarget(); - fail("Should throw NoSuchElementException"); - } - catch (NoSuchElementException ex) { - // desired - } + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( + targetSource::getTarget); // lets now release an object and try to acquire a new one targetSource.releaseTarget(pooledInstances[9]); diff --git a/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java index 5e1f521edc8..e43b67037f8 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java @@ -35,9 +35,9 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Integration tests for handling JSR-303 {@link javax.inject.Qualifier} annotations. @@ -62,14 +62,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -82,14 +80,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -102,14 +98,9 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e instanceof UnsatisfiedDependencyException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired")); } @Test @@ -212,14 +203,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -236,14 +225,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -260,14 +247,9 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e instanceof UnsatisfiedDependencyException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired")); } @Test @@ -370,14 +352,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -449,14 +429,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -507,14 +485,12 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -533,14 +509,9 @@ public class InjectAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e instanceof UnsatisfiedDependencyException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired")); } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java b/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java index 44e45ffbccc..3c3460f47b9 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java @@ -34,9 +34,9 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Integration tests for handling {@link Qualifier} annotations. @@ -63,14 +63,13 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -83,14 +82,13 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); + } @Test @@ -103,14 +101,9 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e instanceof UnsatisfiedDependencyException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired")); } @Test @@ -213,14 +206,12 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -237,14 +228,12 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -261,14 +250,9 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e instanceof UnsatisfiedDependencyException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired")); } @Test @@ -391,14 +375,12 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -470,14 +452,12 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -528,14 +508,12 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThat(ex.getBeanName()).isEqualTo("autowired"); + }); } @Test @@ -597,14 +575,9 @@ public class QualifierAnnotationAutowireContextTests { context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); - try { - context.refresh(); - fail("expected BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e instanceof UnsatisfiedDependencyException); - assertEquals("autowired", e.getBeanName()); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired")); } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java index 3dd12da6dbc..ca32c8dee90 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java @@ -35,10 +35,10 @@ import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.util.ClassUtils.convertClassNameToResourcePath; /** @@ -59,13 +59,9 @@ public class QualifierAnnotationTests { BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", NonQualifiedTestBean.class); - try { - context.refresh(); - fail("Should have thrown a BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getMessage().contains("found 6")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .withMessageContaining("found 6"); } @Test @@ -196,13 +192,9 @@ public class QualifierAnnotationTests { BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAttributesTestBean.class); - try { - context.refresh(); - fail("should have thrown a BeanCreationException"); - } - catch (BeanCreationException e) { - assertTrue(e.getMessage().contains("found 6")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .withMessageContaining("found 6"); } @Test diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java index 166fceaf076..d5b71b005c0 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java @@ -67,6 +67,8 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.SerializationTestUtils; 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.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @@ -76,7 +78,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Miscellaneous tests for XML bean definitions. @@ -428,13 +429,8 @@ public class XmlBeanFactoryTests { assertTrue(tbs.containsKey("inheritedTestBeanSingleton")); // abstract bean should throw exception on creation attempt - try { - parent.getBean("inheritedTestBeanWithoutClass"); - fail("Should have thrown BeanIsAbstractException"); - } - catch (BeanIsAbstractException ex) { - // expected - } + assertThatExceptionOfType(BeanIsAbstractException.class).isThrownBy(() -> + parent.getBean("inheritedTestBeanWithoutClass")); // non-abstract bean should work, even if it serves as parent assertTrue(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean); @@ -484,15 +480,10 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); - try { - child.getBean("bogusParent", TestBean.class); - fail(); - } - catch (BeanDefinitionStoreException ex) { - // check exception message contains the name - assertTrue(ex.getMessage().contains("bogusParent")); - assertTrue(ex.getCause() instanceof NoSuchBeanDefinitionException); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + child.getBean("bogusParent", TestBean.class)) + .withMessageContaining("bogusParent") + .withCauseInstanceOf(NoSuchBeanDefinitionException.class); } /** @@ -584,13 +575,9 @@ public class XmlBeanFactoryTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); reader.loadBeanDefinitions(REFTYPES_CONTEXT); - try { - xbf.getBean("jenny"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.contains(BeanCurrentlyInCreationException.class)); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("jenny")) + .matches(ex -> ex.contains(BeanCurrentlyInCreationException.class)); } @Test @@ -600,13 +587,9 @@ public class XmlBeanFactoryTests { reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); reader.loadBeanDefinitions(REFTYPES_CONTEXT); xbf.addBeanPostProcessor(new WrappingPostProcessor()); - try { - xbf.getBean("jenny"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.contains(BeanCurrentlyInCreationException.class)); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("jenny")) + .matches(ex -> ex.contains(BeanCurrentlyInCreationException.class)); } @Test @@ -658,11 +641,12 @@ public class XmlBeanFactoryTests { assertEquals(5, xbf.getSingletonCount()); } - @Test(expected = BeanCreationException.class) + @Test public void noSuchFactoryBeanMethod() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(NO_SUCH_FACTORY_METHOD_CONTEXT); - assertNotNull(xbf.getBean("defaultTestBean")); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("defaultTestBean")); } @Test @@ -681,31 +665,24 @@ public class XmlBeanFactoryTests { public void testInitMethodThrowsException() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); - try { - xbf.getBean("init-method2"); - fail(); - } - catch (BeanCreationException ex) { - assertTrue(ex.getResourceDescription().contains("initializers.xml")); - assertEquals("init-method2", ex.getBeanName()); - assertTrue(ex.getCause() instanceof IOException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("init-method2")) + .withCauseInstanceOf(IOException.class) + .satisfies(ex -> { + assertThat(ex.getResourceDescription()).contains("initializers.xml"); + assertThat(ex.getBeanName()).isEqualTo("init-method2"); + }); } @Test public void testNoSuchInitMethod() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); - try { - xbf.getBean("init-method3"); - fail(); - } - catch (FatalBeanException ex) { - // check message is helpful - assertTrue(ex.getMessage().contains("initializers.xml")); - assertTrue(ex.getMessage().contains("init-method3")); - assertTrue(ex.getMessage().contains("init")); - } + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + xbf.getBean("init-method3")) + .withMessageContaining("initializers.xml") + .withMessageContaining("init-method3") + .withMessageContaining("init"); } /** @@ -766,16 +743,18 @@ public class XmlBeanFactoryTests { } } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void noSuchXmlFile() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT)); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void invalidXmlFile() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT)); } @Test @@ -832,13 +811,8 @@ public class XmlBeanFactoryTests { assertEquals(kerry, rod3a.getSpouse2()); assertEquals(other, rod3a.getOther()); - try { - xbf.getBean("rod4", ConstructorDependenciesBean.class); - fail("Must have thrown a FatalBeanException"); - } - catch (FatalBeanException expected) { - // expected - } + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + xbf.getBean("rod4", ConstructorDependenciesBean.class)); DependenciesBean rod5 = (DependenciesBean) xbf.getBean("rod5"); // Should not have been autowired @@ -1021,18 +995,20 @@ public class XmlBeanFactoryTests { assertEquals(File.separator + "test", file.getPath()); } - @Test(expected = BeanCreationException.class) + @Test public void throwsExceptionOnTooManyArguments() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); - xbf.getBean("rod7", ConstructorDependenciesBean.class); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("rod7", ConstructorDependenciesBean.class)); } - @Test(expected = UnsatisfiedDependencyException.class) + @Test public void throwsExceptionOnAmbiguousResolution() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); - xbf.getBean("rod8", ConstructorDependenciesBean.class); + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> + xbf.getBean("rod8", ConstructorDependenciesBean.class)); } @Test @@ -1117,15 +1093,11 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT); // cool, no errors, so the rubbish class name in the bean def was not resolved - try { - // let's resolve the bean definition; must blow up - factory.getBean("classNotFound"); - fail("Must have thrown a CannotLoadBeanClassException"); - } - catch (CannotLoadBeanClassException ex) { - assertTrue(ex.getResourceDescription().contains("classNotFound.xml")); - assertTrue(ex.getCause() instanceof ClassNotFoundException); - } + // let's resolve the bean definition; must blow up + assertThatExceptionOfType(CannotLoadBeanClassException.class).isThrownBy(() -> + factory.getBean("classNotFound")) + .withCauseInstanceOf(ClassNotFoundException.class) + .satisfies(ex -> assertThat(ex.getResourceDescription()).contains("classNotFound.xml")); } @Test @@ -1193,10 +1165,11 @@ public class XmlBeanFactoryTests { xbf.getBean("resource2", ResourceTestBean.class); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void recursiveImport() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT)); } /** @@ -1368,15 +1341,10 @@ public class XmlBeanFactoryTests { public void testRejectsOverrideOfBogusMethodName() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); - try { - reader.loadBeanDefinitions(INVALID_NO_SUCH_METHOD_CONTEXT); - xbf.getBean("constructorOverrides"); - fail("Shouldn't allow override of bogus method"); - } - catch (BeanDefinitionStoreException ex) { - // Check that the bogus method name was included in the error message - assertTrue("Bogus method name correctly reported", ex.getMessage().contains("bogusMethod")); - } + reader.loadBeanDefinitions(INVALID_NO_SUCH_METHOD_CONTEXT); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + xbf.getBean("constructorOverrides")) + .withMessageContaining("bogusMethod"); } @Test @@ -1480,15 +1448,9 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBean"); bd.setLenientConstructorResolution(false); - try { - xbf.getBean("lenientDependencyTestBean"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - ex.printStackTrace(); - assertTrue(ex.getMostSpecificCause().getMessage().contains("Ambiguous")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("lenientDependencyTestBean")) + .satisfies(ex -> assertThat(ex.getMostSpecificCause().getMessage()).contains("Ambiguous")); } @Test @@ -1497,15 +1459,9 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBeanFactoryMethod"); bd.setLenientConstructorResolution(false); - try { - xbf.getBean("lenientDependencyTestBeanFactoryMethod"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - ex.printStackTrace(); - assertTrue(ex.getMostSpecificCause().getMessage().contains("Ambiguous")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + xbf.getBean("lenientDependencyTestBeanFactoryMethod")) + .satisfies(ex -> assertThat(ex.getMostSpecificCause().getMessage()).contains("Ambiguous")); } @Test @@ -1581,25 +1537,17 @@ public class XmlBeanFactoryTests { @Test public void testWithDuplicateName() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); - try { - new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAMES_CONTEXT); - fail("Duplicate name not detected"); - } - catch (BeansException ex) { - assertTrue(ex.getMessage().contains("Bean name 'foo'")); - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAMES_CONTEXT)) + .withMessageContaining("Bean name 'foo'"); } @Test public void testWithDuplicateNameInAlias() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); - try { - new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAME_IN_ALIAS_CONTEXT); - fail("Duplicate name not detected"); - } - catch (BeansException e) { - assertTrue(e.getMessage().contains("Bean name 'foo'")); - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAME_IN_ALIAS_CONTEXT)) + .withMessageContaining("Bean name 'foo'"); } @Test @@ -1676,9 +1624,7 @@ public class XmlBeanFactoryTests { @Override public void afterPropertiesSet() { - if (this.initMethodInvoked) { - fail(); - } + assertThat(this.initMethodInvoked).isFalse(); if (this.afterPropertiesSetInvoked) { throw new IllegalStateException("Already initialized"); } @@ -1687,9 +1633,7 @@ public class XmlBeanFactoryTests { /** Init method */ public void customInit() throws IOException { - if (!this.afterPropertiesSetInvoked) { - fail(); - } + assertThat(this.afterPropertiesSetInvoked).isTrue(); if (this.initMethodInvoked) { throw new IllegalStateException("Already customInitialized"); } @@ -1698,9 +1642,7 @@ public class XmlBeanFactoryTests { @Override public void destroy() { - if (this.customDestroyed) { - fail(); - } + assertThat(this.customDestroyed).isFalse(); if (this.destroyed) { throw new IllegalStateException("Already destroyed"); } @@ -1708,9 +1650,7 @@ public class XmlBeanFactoryTests { } public void customDestroy() { - if (!this.destroyed) { - fail(); - } + assertThat(this.destroyed).isTrue(); if (this.customDestroyed) { throw new IllegalStateException("Already customDestroyed"); } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java index e9a8aa77dad..d2dc953c4c1 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java @@ -60,10 +60,11 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for custom XML namespace handler implementations. @@ -126,13 +127,9 @@ public class CustomNamespaceHandlerTests { String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.class); assertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance")); assertEquals(ApplicationListener.class, this.beanFactory.getType("debuggingTestBeanNoInstance")); - try { - this.beanFactory.getBean("debuggingTestBeanNoInstance"); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getRootCause() instanceof BeanInstantiationException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + this.beanFactory.getBean("debuggingTestBeanNoInstance")) + .satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(BeanInstantiationException.class)); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java b/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java index 5d047860105..60c5e13c95f 100644 --- a/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java +++ b/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java @@ -46,7 +46,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -225,7 +224,7 @@ public class CacheReproTests { @Cacheable("smallCache") public List single(int id) { if (this.multipleCount > 0) { - fail("Called too many times"); + throw new AssertionError("Called too many times"); } this.multipleCount++; return Collections.emptyList(); @@ -237,7 +236,7 @@ public class CacheReproTests { @Cacheable(cacheNames = "smallCache", unless = "#result.size() > 3")}) public List multiple(int id) { if (this.multipleCount > 0) { - fail("Called too many times"); + throw new AssertionError("Called too many times"); } this.multipleCount++; return Collections.emptyList(); 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 f449ff03fd6..2f26c1e4d66 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 @@ -16,7 +16,6 @@ package org.springframework.cache.config; -import java.io.IOException; import java.util.Collection; import java.util.UUID; @@ -30,6 +29,8 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.context.ConfigurableApplicationContext; +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; @@ -39,7 +40,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Abstract cache annotation tests (containing several reusable methods). @@ -336,49 +336,28 @@ public abstract class AbstractCacheAnnotationTests { public void testCheckedThrowable(CacheableService service) throws Exception { String arg = UUID.randomUUID().toString(); - try { - service.throwChecked(arg); - fail("Excepted exception"); - } - catch (Exception ex) { - assertEquals("Wrong exception type", IOException.class, ex.getClass()); - assertEquals(arg, ex.getMessage()); - } + assertThatIOException().isThrownBy(() -> + service.throwChecked(arg)) + .withMessage(arg); } public void testUncheckedThrowable(CacheableService service) throws Exception { - try { - service.throwUnchecked(1L); - fail("Excepted exception"); - } - catch (RuntimeException ex) { - assertEquals("Wrong exception type", UnsupportedOperationException.class, ex.getClass()); - assertEquals("1", ex.getMessage()); - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.throwUnchecked(1L)) + .withMessage("1"); } public void testCheckedThrowableSync(CacheableService service) throws Exception { String arg = UUID.randomUUID().toString(); - try { - service.throwCheckedSync(arg); - fail("Excepted exception"); - } - catch (Exception ex) { - ex.printStackTrace(); - assertEquals("Wrong exception type", IOException.class, ex.getClass()); - assertEquals(arg, ex.getMessage()); - } + assertThatIOException().isThrownBy(() -> + service.throwCheckedSync(arg)) + .withMessage(arg); } public void testUncheckedThrowableSync(CacheableService service) throws Exception { - try { - service.throwUncheckedSync(1L); - fail("Excepted exception"); - } - catch (RuntimeException ex) { - assertEquals("Wrong exception type", UnsupportedOperationException.class, ex.getClass()); - assertEquals("1", ex.getMessage()); - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + service.throwUncheckedSync(1L)) + .withMessage("1"); } public void testNullArg(CacheableService service) { @@ -709,14 +688,9 @@ public abstract class AbstractCacheAnnotationTests { @Test public void testUnknownCustomKeyGenerator() { - try { - Object param = new Object(); - this.cs.unknownCustomKeyGenerator(param); - fail("should have failed with NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + Object param = new Object(); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + this.cs.unknownCustomKeyGenerator(param)); } @Test @@ -732,14 +706,9 @@ public abstract class AbstractCacheAnnotationTests { @Test public void testUnknownCustomCacheManager() { - try { - Object param = new Object(); - this.cs.unknownCustomCacheManager(param); - fail("should have failed with NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + Object param = new Object(); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + this.cs.unknownCustomCacheManager(param)); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceParserTests.java b/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceParserTests.java index 3b47282b3ab..0a9383a13ee 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceParserTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceParserTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.context.support.GenericXmlApplicationContext; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * AOP advice specific parsing tests. @@ -32,13 +32,9 @@ public class CacheAdviceParserTests { @Test public void keyAndKeyGeneratorCannotBeSetTogether() { - try { - new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml"); - fail("Should have failed to load context, one advise define both a key and a key generator"); - } - catch (BeanDefinitionStoreException ex) { - // TODO better exception handling - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml")); + // TODO better exception handling } } diff --git a/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java b/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java index a2bb9ecc07f..a0d8fc43b36 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java @@ -34,9 +34,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * @author Stephane Nicoll @@ -74,17 +73,9 @@ public class CustomInterceptorTests { @Test public void customInterceptorAppliesWithCheckedException() { - try { - this.cs.throwChecked(0L); - fail("Should have failed"); - } - catch (RuntimeException e) { - assertNotNull("missing original exception", e.getCause()); - assertEquals(IOException.class, e.getCause().getClass()); - } - catch (Exception e) { - fail("Wrong exception type " + e); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + this.cs.throwChecked(0L)) + .withCauseExactlyInstanceOf(IOException.class); } diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheResolverCustomizationTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheResolverCustomizationTests.java index 77b0f12d64e..a2d1e4cf1a8 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheResolverCustomizationTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheResolverCustomizationTests.java @@ -39,9 +39,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.lang.Nullable; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.springframework.cache.CacheTestUtils.assertCacheHit; import static org.springframework.cache.CacheTestUtils.assertCacheMiss; @@ -134,24 +134,16 @@ public class CacheResolverCustomizationTests { @Test public void noCacheResolved() { Method method = ReflectionUtils.findMethod(SimpleService.class, "noCacheResolved", Object.class); - try { - this.simpleService.noCacheResolved(new Object()); - fail("Should have failed, no cache resolved"); - } - catch (IllegalStateException ex) { - assertTrue("Reference to the method must be contained in the message", ex.getMessage().contains(method.toString())); - } + assertThatIllegalStateException().isThrownBy(() -> + this.simpleService.noCacheResolved(new Object())) + .withMessageContaining(method.toString()); } @Test public void unknownCacheResolver() { - try { - this.simpleService.unknownCacheResolver(new Object()); - fail("Should have failed, no cache resolver with that name"); - } - catch (NoSuchBeanDefinitionException ex) { - assertEquals("Wrong bean name in exception", "unknownCacheResolver", ex.getBeanName()); - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + this.simpleService.unknownCacheResolver(new Object())) + .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("unknownCacheResolver")); } 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 d337de38d22..dc22dc8adc2 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 @@ -36,13 +36,14 @@ import org.springframework.expression.EvaluationContext; import org.springframework.expression.spel.standard.SpelExpressionParser; 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; -import static org.junit.Assert.fail; /** * @author Costin Leau @@ -124,13 +125,9 @@ public class ExpressionEvaluatorTests { @Test public void unavailableReturnValue() { EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.RESULT_UNAVAILABLE); - try { - new SpelExpressionParser().parseExpression("#result").getValue(context); - fail("Should have failed to parse expression, result not available"); - } - catch (VariableNotAvailableException e) { - assertEquals("wrong variable name", "result", e.getName()); - } + assertThatExceptionOfType(VariableNotAvailableException.class).isThrownBy(() -> + new SpelExpressionParser().parseExpression("#result").getValue(context)) + .satisfies(ex -> assertThat(ex.getName()).isEqualTo("result")); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java index bd7ba0fe3a8..2aafcbc0572 100644 --- a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java @@ -30,6 +30,7 @@ import org.springframework.beans.factory.xml.AbstractListableBeanFactoryTests; import org.springframework.tests.sample.beans.LifecycleBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -134,12 +135,12 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe assertTrue("Destroyed", lb.isDestroyed()); } - @Test(expected = NoSuchMessageException.class) + @Test public void messageSource() throws NoSuchMessageException { assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault())); assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault())); - - applicationContext.getMessage("code0", null, Locale.getDefault()); + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + applicationContext.getMessage("code0", null, Locale.getDefault())); } @Test 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 d3b7ab918fc..fdb18203417 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,6 +34,7 @@ import org.springframework.core.ResolvableType; import org.springframework.util.ObjectUtils; import static java.lang.String.format; +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; @@ -45,7 +46,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.util.StringUtils.uncapitalize; /** @@ -106,13 +106,9 @@ public class AnnotationConfigApplicationContextTests { // attempt to retrieve a bean that does not exist Class targetType = Pattern.class; - try { - context.getBean(targetType); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - assertThat(ex.getMessage(), containsString(format("No qualifying bean of type '%s'", targetType.getName()))); - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + context.getBean(targetType)) + .withMessageContaining(format("No qualifying bean of type '%s'", targetType.getName())); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java index 3bd97f852ee..147a7d19941 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java @@ -29,6 +29,7 @@ import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.springframework.context.annotation.ScopedProxyMode.INTERFACES; @@ -117,14 +118,16 @@ public class AnnotationScopeMetadataResolverTests { assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithNullScopedProxyMode() { - new AnnotationScopeMetadataResolver(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new AnnotationScopeMetadataResolver(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setScopeAnnotationTypeWithNullType() { - scopeMetadataResolver.setScopeAnnotationType(null); + assertThatIllegalArgumentException().isThrownBy(() -> + scopeMetadataResolver.setScopeAnnotationType(null)); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java index 5c971f2e136..02cac0bc3e4 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java @@ -39,11 +39,13 @@ import org.springframework.core.type.filter.AssignableTypeFilter; import org.springframework.stereotype.Component; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Mark Fisher @@ -149,16 +151,11 @@ public class ClassPathBeanDefinitionScannerTests { GenericApplicationContext context = new GenericApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.setIncludeAnnotationConfig(false); - try { - scanner.scan("org.springframework.context.annotation3"); - scanner.scan(BASE_PACKAGE); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - assertTrue(ex.getMessage().contains("stubFooDao")); - assertTrue(ex.getMessage().contains(StubFooDao.class.getName())); - } + scanner.scan("org.springframework.context.annotation3"); + assertThatIllegalStateException().isThrownBy(() -> + scanner.scan(BASE_PACKAGE)) + .withMessageContaining("stubFooDao") + .withMessageContaining(StubFooDao.class.getName()); } @Test @@ -214,16 +211,12 @@ public class ClassPathBeanDefinitionScannerTests { GenericApplicationContext context = new GenericApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.setIncludeAnnotationConfig(false); - try { - scanner.scan("org.springframework.context.annotation2"); - scanner.scan(BASE_PACKAGE); - fail("Must have thrown IllegalStateException"); - } - catch (IllegalStateException expected) { - assertTrue(expected.getMessage().contains("myNamedDao")); - assertTrue(expected.getMessage().contains(NamedStubDao.class.getName())); - assertTrue(expected.getMessage().contains(NamedStubDao2.class.getName())); - } + scanner.scan("org.springframework.context.annotation2"); + assertThatIllegalStateException().isThrownBy(() -> + scanner.scan(BASE_PACKAGE)) + .withMessageContaining("myNamedDao") + .withMessageContaining(NamedStubDao.class.getName()) + .withMessageContaining(NamedStubDao2.class.getName()); } @Test @@ -472,15 +465,10 @@ public class ClassPathBeanDefinitionScannerTests { scanner.setBeanNameGenerator(new TestBeanNameGenerator()); scanner.setAutowireCandidatePatterns("*NoSuchDao"); scanner.scan(BASE_PACKAGE); - - try { - context.refresh(); - context.getBean("fooService"); - fail("BeanCreationException expected; fooDao should not have been an autowire-candidate"); - } - catch (BeanCreationException expected) { - assertTrue(expected.getMostSpecificCause() instanceof NoSuchBeanDefinitionException); - } + context.refresh(); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + context.getBean("fooService")) + .satisfies(ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(NoSuchBeanDefinitionException.class)); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java index bff4257255d..c5b52c1a1f4 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java @@ -23,12 +23,12 @@ import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.GenericApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Mark Fisher @@ -123,13 +123,8 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireByTypeTests.xml"); - try { - context.refresh(); - fail("expected exception due to multiple matches for byType autowiring"); - } - catch (UnsatisfiedDependencyException ex) { - // expected - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + context::refresh); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java index c77217b04f2..4b488f9ad8b 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java @@ -23,10 +23,10 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Mark Fisher @@ -51,26 +51,16 @@ public class ComponentScanParserWithUserDefinedStrategiesTests { @Test public void testInvalidConstructorBeanNameGenerator() { - try { + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> new ClassPathXmlApplicationContext( - "org/springframework/context/annotation/invalidConstructorNameGeneratorTests.xml"); - fail("should have failed: no-arg constructor is required"); - } - catch (BeansException ex) { - // expected - } + "org/springframework/context/annotation/invalidConstructorNameGeneratorTests.xml")); } @Test public void testInvalidClassNameScopeMetadataResolver() { - try { - new ClassPathXmlApplicationContext( - "org/springframework/context/annotation/invalidClassNameScopeResolverTests.xml"); - fail("should have failed: no such class"); - } - catch (BeansException ex) { - // expected - } + assertThatExceptionOfType(BeansException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext( + "org/springframework/context/annotation/invalidClassNameScopeResolverTests.xml")); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java index 61a30352fa7..69750f37873 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java @@ -64,12 +64,13 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Chris Beams @@ -318,13 +319,8 @@ public class ConfigurationClassPostProcessorTests { ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.setEnvironment(new StandardEnvironment()); pp.postProcessBeanFactory(beanFactory); - try { - beanFactory.getBean(SimpleComponent.class); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + beanFactory.getBean(SimpleComponent.class)); } @Test @@ -374,15 +370,11 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(SingletonBeanConfig.class)); beanFactory.setAllowBeanDefinitionOverriding(false); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); - try { - pp.postProcessBeanFactory(beanFactory); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - assertTrue(ex.getMessage().contains("bar")); - assertTrue(ex.getMessage().contains("SingletonBeanConfig")); - assertTrue(ex.getMessage().contains(TestBean.class.getName())); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + pp.postProcessBeanFactory(beanFactory)) + .withMessageContaining("bar") + .withMessageContaining("SingletonBeanConfig") + .withMessageContaining(TestBean.class.getName()); } @Test @@ -420,16 +412,12 @@ public class ConfigurationClassPostProcessorTests { ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - try { - beanFactory.getBean(Bar.class); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("OverridingSingletonBeanConfig.foo")); - assertTrue(ex.getMessage().contains(ExtendedFoo.class.getName())); - assertTrue(ex.getMessage().contains(Foo.class.getName())); - assertTrue(ex.getMessage().contains("InvalidOverridingSingletonBeanConfig")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + beanFactory.getBean(Bar.class)) + .withMessageContaining("OverridingSingletonBeanConfig.foo") + .withMessageContaining(ExtendedFoo.class.getName()) + .withMessageContaining(Foo.class.getName()) + .withMessageContaining("InvalidOverridingSingletonBeanConfig"); } @Test // SPR-15384 @@ -479,19 +467,11 @@ public class ConfigurationClassPostProcessorTests { DefaultListableBeanFactory bf2 = new DefaultListableBeanFactory(); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(bf1); // first invocation -- should succeed - try { - pp.postProcessBeanFactory(bf1); // second invocation for bf1 -- should throw - fail("expected exception"); - } - catch (IllegalStateException ex) { - } + assertThatIllegalStateException().isThrownBy(() -> + pp.postProcessBeanFactory(bf1)); // second invocation for bf1 -- should throw pp.postProcessBeanFactory(bf2); // first invocation for bf2 -- should succeed - try { - pp.postProcessBeanFactory(bf2); // second invocation for bf2 -- should throw - fail("expected exception"); - } - catch (IllegalStateException ex) { - } + assertThatIllegalStateException().isThrownBy(() -> + pp.postProcessBeanFactory(bf2)); // second invocation for bf2 -- should throw } @Test @@ -985,24 +965,16 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("configClass1", new RootBeanDefinition(A.class)); beanFactory.registerBeanDefinition("configClass2", new RootBeanDefinition(AStrich.class)); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); - try { - beanFactory.preInstantiateSingletons(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("Circular reference")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + beanFactory::preInstantiateSingletons) + .withMessageContaining("Circular reference"); } @Test public void testCircularDependencyWithApplicationContext() { - try { - new AnnotationConfigApplicationContext(A.class, AStrich.class); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("Circular reference")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + new AnnotationConfigApplicationContext(A.class, AStrich.class)) + .withMessageContaining("Circular reference"); } @Test @@ -1106,10 +1078,12 @@ public class ConfigurationClassPostProcessorTests { assertSame(ctx.getBean(TestBean.class), bean.getTestBean()); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void testNameClashBetweenConfigurationClassAndBean() { - ApplicationContext ctx = new AnnotationConfigApplicationContext(MyTestBean.class); - ctx.getBean("myTestBean", TestBean.class); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> { + ApplicationContext ctx = new AnnotationConfigApplicationContext(MyTestBean.class); + ctx.getBean("myTestBean", TestBean.class); + }); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ImportVersusDirectRegistrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ImportVersusDirectRegistrationTests.java index cb273551a63..21c56c38dc2 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ImportVersusDirectRegistrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ImportVersusDirectRegistrationTests.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. @@ -21,36 +21,41 @@ import org.junit.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.support.RootBeanDefinition; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Andy Wilkinson */ public class ImportVersusDirectRegistrationTests { - @Test(expected = NoSuchBeanDefinitionException.class) + @Test public void thingIsNotAvailableWhenOuterConfigurationIsRegisteredDirectly() { try (AnnotationConfigApplicationContext directRegistration = new AnnotationConfigApplicationContext()) { directRegistration.register(AccidentalLiteConfiguration.class); directRegistration.refresh(); - directRegistration.getBean(Thing.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + directRegistration.getBean(Thing.class)); } } - @Test(expected = NoSuchBeanDefinitionException.class) + @Test public void thingIsNotAvailableWhenOuterConfigurationIsRegisteredWithClassName() { try (AnnotationConfigApplicationContext directRegistration = new AnnotationConfigApplicationContext()) { directRegistration.registerBeanDefinition("config", new RootBeanDefinition(AccidentalLiteConfiguration.class.getName())); directRegistration.refresh(); - directRegistration.getBean(Thing.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + directRegistration.getBean(Thing.class)); } } - @Test(expected = NoSuchBeanDefinitionException.class) + @Test public void thingIsNotAvailableWhenOuterConfigurationIsImported() { try (AnnotationConfigApplicationContext viaImport = new AnnotationConfigApplicationContext()) { viaImport.register(Importer.class); viaImport.refresh(); - viaImport.getBean(Thing.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + viaImport.getBean(Thing.class)); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/InvalidConfigurationClassDefinitionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/InvalidConfigurationClassDefinitionTests.java index ece97986045..77a7d2c0dbb 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/InvalidConfigurationClassDefinitionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/InvalidConfigurationClassDefinitionTests.java @@ -21,8 +21,7 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; /** @@ -43,14 +42,10 @@ public class InvalidConfigurationClassDefinitionTests { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerBeanDefinition("config", configBeanDef); - try { - ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); - pp.postProcessBeanFactory(beanFactory); - fail("expected exception"); - } - catch (BeanDefinitionParsingException ex) { - assertTrue(ex.getMessage(), ex.getMessage().contains("Remove the final modifier")); - } + ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> + pp.postProcessBeanFactory(beanFactory)) + .withMessageContaining("Remove the final modifier"); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java index e62d334e1d1..887f8278fb2 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java @@ -29,12 +29,12 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -133,13 +133,8 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests { FieldResourceInjectionBean bean = (FieldResourceInjectionBean) bf.getBean("annotatedBean"); assertNotNull(bean.getTestBean()); - try { - bean.getTestBean().getName(); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + bean.getTestBean().getName()); } @Test @@ -157,13 +152,8 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests { assertNotNull(bean.getTestBean()); assertNotNull(bean.getTestBeans()); assertTrue(bean.getTestBeans().isEmpty()); - try { - bean.getTestBean().getName(); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + bean.getTestBean().getName()); } 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 2b776493d76..7412886c8bb 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 @@ -65,12 +65,12 @@ import org.springframework.validation.annotation.Validated; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; 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; -import static org.junit.Assert.fail; /** * @author Stephane Nicoll @@ -299,13 +299,9 @@ public class AnnotationDrivenEventListenerTests { @Test public void privateMethodOnCglibProxyFails() throws Exception { - try { - load(CglibProxyWithPrivateMethod.class); - fail("Should have thrown BeanInitializationException"); - } - catch (BeanInitializationException ex) { - assertTrue(ex.getCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(() -> + load(CglibProxyWithPrivateMethod.class)) + .withCauseInstanceOf(IllegalStateException.class); } @Test @@ -331,15 +327,10 @@ public class AnnotationDrivenEventListenerTests { this.eventCollector.assertEvent(proxy.getId(), event); this.eventCollector.assertTotalEventsCount(1); - try { - customScope.active = false; - this.context.publishEvent(new TestEvent()); - fail("Should have thrown IllegalStateException"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.getCause() instanceof IllegalStateException); - } + customScope.active = false; + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + this.context.publishEvent(new TestEvent())) + .withCauseInstanceOf(IllegalStateException.class); } @Test @@ -393,15 +384,11 @@ public class AnnotationDrivenEventListenerTests { TestEvent event = new TestEvent(this, "fail"); ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class); this.eventCollector.assertNoEventReceived(listener); - try { - this.context.publishEvent(event); - fail("An exception should have thrown"); - } - catch (IllegalStateException e) { - assertEquals("Wrong exception", "Test exception", e.getMessage()); - this.eventCollector.assertEvent(listener, event); - this.eventCollector.assertTotalEventsCount(1); - } + assertThatIllegalStateException().isThrownBy(() -> + this.context.publishEvent(event)) + .withMessage("Test exception"); + this.eventCollector.assertEvent(listener, event); + this.eventCollector.assertTotalEventsCount(1); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java index 5edbb3fb178..fdd7dc78588 100644 --- a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java @@ -48,11 +48,12 @@ import org.springframework.scheduling.support.TaskUtils; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -164,13 +165,9 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen RuntimeException thrown = new RuntimeException(); willThrow(thrown).given(listener).onApplicationEvent(evt); - try { - smc.multicastEvent(evt); - fail("Should have thrown RuntimeException"); - } - catch (RuntimeException ex) { - assertSame(thrown, ex); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + smc.multicastEvent(evt)) + .satisfies(ex -> assertThat(ex).isSameAs(thrown)); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java index aa0b8ddc3c3..ee4cd3d745a 100644 --- a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java @@ -31,6 +31,7 @@ import org.springframework.context.support.StaticApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -49,35 +50,42 @@ public class EventPublicationInterceptorTests { this.publisher = mock(ApplicationEventPublisher.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNoApplicationEventClassSupplied() throws Exception { EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); interceptor.setApplicationEventPublisher(this.publisher); - interceptor.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + interceptor::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNonApplicationEventClassSupplied() throws Exception { EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); interceptor.setApplicationEventPublisher(this.publisher); - interceptor.setApplicationEventClass(getClass()); - interceptor.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy(() -> { + interceptor.setApplicationEventClass(getClass()); + interceptor.afterPropertiesSet(); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithAbstractStraightApplicationEventClassSupplied() throws Exception { EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); interceptor.setApplicationEventPublisher(this.publisher); - interceptor.setApplicationEventClass(ApplicationEvent.class); - interceptor.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy(() -> { + interceptor.setApplicationEventClass(ApplicationEvent.class); + interceptor.afterPropertiesSet(); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithApplicationEventClassThatDoesntExposeAValidCtor() throws Exception { EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); interceptor.setApplicationEventPublisher(this.publisher); - interceptor.setApplicationEventClass(TestEventWithNoValidOneArgObjectCtor.class); - interceptor.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy(() -> { + interceptor.setApplicationEventClass(TestEventWithNoValidOneArgObjectCtor.class); + interceptor.afterPropertiesSet(); + }); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java b/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java index 480a171abba..e8d0b34f310 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java @@ -21,7 +21,6 @@ import org.junit.Test; import org.springframework.beans.factory.BeanIsNotAFactoryException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.expression.FactoryBeanAccessTests.SimpleBeanResolver.Boat; import org.springframework.context.expression.FactoryBeanAccessTests.SimpleBeanResolver.CarFactoryBean; import org.springframework.context.support.StaticApplicationContext; import org.springframework.expression.AccessException; @@ -30,8 +29,8 @@ import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * Unit tests for expressions accessing beans and factory beans. @@ -51,34 +50,19 @@ public class FactoryBeanAccessTests { expr = new SpelExpressionParser().parseRaw("@boat.colour"); assertEquals("blue",expr.getValue(context)); - expr = new SpelExpressionParser().parseRaw("&boat.class.name"); - try { - assertEquals(Boat.class.getName(), expr.getValue(context)); - fail("Expected BeanIsNotAFactoryException"); - } - catch (BeanIsNotAFactoryException binafe) { - // success - } + Expression notFactoryExpr = new SpelExpressionParser().parseRaw("&boat.class.name"); + assertThatExceptionOfType(BeanIsNotAFactoryException.class).isThrownBy(() -> + notFactoryExpr.getValue(context)); // No such bean - try { - expr = new SpelExpressionParser().parseRaw("@truck"); - assertEquals("red", expr.getValue(context)); - fail("Expected NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException nsbde) { - // success - } + Expression noBeanExpr = new SpelExpressionParser().parseRaw("@truck"); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + noBeanExpr.getValue(context)); // No such factory bean - try { - expr = new SpelExpressionParser().parseRaw("&truck"); - assertEquals(CarFactoryBean.class.getName(), expr.getValue(context)); - fail("Expected NoSuchBeanDefinitionException"); - } - catch (NoSuchBeanDefinitionException nsbde) { - // success - } + Expression noFactoryBeanExpr = new SpelExpressionParser().parseRaw("&truck"); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> + noFactoryBeanExpr.getValue(context)); } static class SimpleBeanResolver diff --git a/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java index 3e3e3dfefb3..cbe3a852726 100644 --- a/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.context.support.GenericGroovyApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -70,9 +71,10 @@ public class GroovyApplicationContextTests { assertEquals("SpringSource", company); } - @Test(expected = BeanDefinitionParsingException.class) + @Test public void testConfigFileParsingError() { - new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext-error.groovy"); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> + new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext-error.groovy")); } } diff --git a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java index b0f18672ebe..0b5eab7b00f 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java @@ -43,12 +43,13 @@ import org.springframework.tests.sample.beans.ResourceTestBean; import org.springframework.util.FileCopyUtils; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -141,39 +142,37 @@ public class ClassPathXmlApplicationContextTests { public void testContextWithInvalidValueType() throws IOException { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] {INVALID_VALUE_TYPE_CONTEXT}, false); - try { - context.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.contains(TypeMismatchException.class)); - assertTrue(ex.toString().contains("someMessageSource")); - assertTrue(ex.toString().contains("useCodeAsDefaultMessage")); - checkExceptionFromInvalidValueType(ex); - checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex)); - assertFalse(context.isActive()); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh) + .satisfies(ex -> { + assertThat(ex.contains(TypeMismatchException.class)).isTrue(); + assertThat(ex.toString()).contains("someMessageSource", "useCodeAsDefaultMessage"); + checkExceptionFromInvalidValueType(ex); + checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex)); + assertFalse(context.isActive()); + }); } - private void checkExceptionFromInvalidValueType(Throwable ex) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ex.printStackTrace(new PrintStream(baos)); - String dump = FileCopyUtils.copyToString(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()))); - assertTrue(dump.contains("someMessageSource")); - assertTrue(dump.contains("useCodeAsDefaultMessage")); + private void checkExceptionFromInvalidValueType(Throwable ex) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ex.printStackTrace(new PrintStream(baos)); + String dump = FileCopyUtils.copyToString(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()))); + assertTrue(dump.contains("someMessageSource")); + assertTrue(dump.contains("useCodeAsDefaultMessage")); + } + catch (IOException ioex) { + throw new IllegalStateException(ioex); + } } @Test public void testContextWithInvalidLazyClass() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(INVALID_CLASS_CONTEXT, getClass()); assertTrue(ctx.containsBean("someMessageSource")); - try { - ctx.getBean("someMessageSource"); - fail("Should have thrown CannotLoadBeanClassException"); - } - catch (CannotLoadBeanClassException ex) { - assertTrue(ex.contains(ClassNotFoundException.class)); - } + assertThatExceptionOfType(CannotLoadBeanClassException.class).isThrownBy(() -> + ctx.getBean("someMessageSource")) + .satisfies(ex -> assertThat(ex.contains(ClassNotFoundException.class)).isTrue()); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java index 091ab80d853..89d406dd7c2 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,6 +34,7 @@ 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.assertThatIllegalArgumentException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertTrue; @@ -94,13 +95,14 @@ public class ConversionServiceFactoryBeanTests { assertTrue(service.canConvert(String.class, Baz.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void createDefaultConversionServiceWithInvalidSupplements() { ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); Set converters = new HashSet<>(); converters.add("bogus"); factory.setConverters(converters); - factory.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + factory::afterPropertiesSet); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java index d0959bb4eec..a819d5e0125 100644 --- a/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java @@ -24,13 +24,14 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -48,13 +49,8 @@ public class GenericApplicationContextTests { assertSame(ac.getBean("testBean"), ac.getBean(String.class)); assertSame(ac.getBean("testBean"), ac.getBean(CharSequence.class)); - try { - assertSame(ac.getBean("testBean"), ac.getBean(Object.class)); - fail("Should have thrown NoUniqueBeanDefinitionException"); - } - catch (NoUniqueBeanDefinitionException ex) { - // expected - } + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> + ac.getBean(Object.class)); } @Test @@ -94,22 +90,13 @@ public class GenericApplicationContextTests { ac.close(); - try { - assertSame(ac.getBean("testBean"), ac.getBean(String.class)); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + ac.getBean(String.class)); - try { - assertSame(ac.getAutowireCapableBeanFactory().getBean("testBean"), - ac.getAutowireCapableBeanFactory().getBean(String.class)); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> { + ac.getAutowireCapableBeanFactory().getBean("testBean"); + ac.getAutowireCapableBeanFactory().getBean(String.class); + }); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java index dbfeee9db66..2b37720cf14 100644 --- a/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java @@ -31,8 +31,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link PropertyResourceConfigurer} implementations requiring @@ -54,20 +53,11 @@ public class PropertyResourceConfigurerIntegrationTests { pvs = new MutablePropertyValues(); pvs.add("location", "${user.dir}/test"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); - try { - ac.refresh(); - fail("Should have thrown BeanInitializationException"); - } - catch (BeanInitializationException ex) { - // expected - assertTrue(ex.getCause() instanceof FileNotFoundException); - // slight hack for Linux/Unix systems - String userDir = StringUtils.cleanPath(System.getProperty("user.dir")); - if (userDir.startsWith("/")) { - userDir = userDir.substring(1); - } - assertTrue(ex.getMessage().contains(userDir)); - } + String userDir = getUserDir(); + assertThatExceptionOfType(BeanInitializationException.class).isThrownBy( + ac::refresh) + .withCauseInstanceOf(FileNotFoundException.class) + .withMessageContaining(userDir); } @Test @@ -79,24 +69,21 @@ public class PropertyResourceConfigurerIntegrationTests { pvs = new MutablePropertyValues(); pvs.add("location", "${user.dir}/test/${user.dir}"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); - try { - ac.refresh(); - fail("Should have thrown BeanInitializationException"); - } - catch (BeanInitializationException ex) { - // expected - assertTrue(ex.getCause() instanceof FileNotFoundException); - // slight hack for Linux/Unix systems - String userDir = StringUtils.cleanPath(System.getProperty("user.dir")); - if (userDir.startsWith("/")) { - userDir = userDir.substring(1); - } - /* the above hack doesn't work since the exception message is created without - the leading / stripped so the test fails. Changed 17/11/04. DD */ - //assertTrue(ex.getMessage().indexOf(userDir + "/test/" + userDir) != -1); - assertTrue(ex.getMessage().contains(userDir + "/test/" + userDir) || + String userDir = getUserDir(); + assertThatExceptionOfType(BeanInitializationException.class).isThrownBy( + ac::refresh) + .withCauseInstanceOf(FileNotFoundException.class) + .matches(ex -> ex.getMessage().contains(userDir + "/test/" + userDir) || ex.getMessage().contains(userDir + "/test//" + userDir)); + } + + private String getUserDir() { + // slight hack for Linux/Unix systems + String userDir = StringUtils.cleanPath(System.getProperty("user.dir")); + if (userDir.startsWith("/")) { + userDir = userDir.substring(1); } + return userDir; } @Test @@ -108,14 +95,9 @@ public class PropertyResourceConfigurerIntegrationTests { pvs = new MutablePropertyValues(); pvs.add("location", "${myprop}/test/${myprop}"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); - try { - ac.refresh(); - fail("Should have thrown BeanInitializationException"); - } - catch (BeanInitializationException ex) { - // expected - assertTrue(ex.getMessage().contains("myprop")); - } + assertThatExceptionOfType(BeanInitializationException.class).isThrownBy( + ac::refresh) + .withMessageContaining("myprop"); } @Test @@ -127,13 +109,8 @@ public class PropertyResourceConfigurerIntegrationTests { pvs = new MutablePropertyValues(); pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${var}"); ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs); - try { - ac.refresh(); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy( + ac::refresh); } @Test @@ -145,13 +122,8 @@ public class PropertyResourceConfigurerIntegrationTests { pvs = new MutablePropertyValues(); pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${m}"); ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs); - try { - ac.refresh(); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy( + ac::refresh); } @Test @@ -163,14 +135,8 @@ public class PropertyResourceConfigurerIntegrationTests { pvs = new MutablePropertyValues(); pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${m2}"); ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs); - try { - ac.refresh(); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - ex.printStackTrace(); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy( + ac::refresh); } @Ignore // this test was breaking after the 3.0 repackaging 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 dfa79cbb43f..4c26e9b4489 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,6 +33,7 @@ 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.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -154,7 +155,7 @@ public class PropertySourcesPlaceholderConfigurerTests { assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); } - @Test(expected = BeanDefinitionStoreException.class) + @Test public void ignoreUnresolvablePlaceholders_falseIsDefault() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("testBean", @@ -164,7 +165,8 @@ public class PropertySourcesPlaceholderConfigurerTests { PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); //pc.setIgnoreUnresolvablePlaceholders(false); // the default - ppc.postProcessBeanFactory(bf); // should throw + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + ppc.postProcessBeanFactory(bf)); } @Test @@ -181,7 +183,7 @@ public class PropertySourcesPlaceholderConfigurerTests { assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); } - @Test(expected = BeanDefinitionStoreException.class) + @Test @SuppressWarnings("serial") public void nestedUnresolvablePlaceholder() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); @@ -194,7 +196,8 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setProperties(new Properties() {{ put("my.name", "${bogus}"); }}); - ppc.postProcessBeanFactory(bf); // should throw + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + ppc.postProcessBeanFactory(bf)); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java index 85771e3b56d..4634db5eb00 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java @@ -29,10 +29,10 @@ import org.springframework.context.MessageSourceResolvable; import org.springframework.context.NoSuchMessageException; import org.springframework.context.i18n.LocaleContextHolder; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -193,16 +193,12 @@ public class ResourceBundleMessageSourceTests { } assertEquals("I'm", ac.getMessage("escaped", new Object[] {"some arg"}, Locale.ENGLISH)); - try { + if (useCodeAsDefaultMessage) { assertEquals("code4", ac.getMessage("code4", null, Locale.GERMAN)); - if (!useCodeAsDefaultMessage) { - fail("Should have thrown NoSuchMessageException"); - } } - catch (NoSuchMessageException ex) { - if (useCodeAsDefaultMessage) { - fail("Should have returned code as default message"); - } + else { + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + ac.getMessage("code4", null, Locale.GERMAN)); } } @@ -278,13 +274,8 @@ public class ResourceBundleMessageSourceTests { ms.setBasename("org/springframework/context/support/messages"); ms.setDefaultEncoding("argh"); ms.setFallbackToSystemLocale(false); - try { - ms.getMessage("code1", null, Locale.ENGLISH); - fail("Should have thrown NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + ms.getMessage("code1", null, Locale.ENGLISH)); } @Test @@ -363,13 +354,8 @@ public class ResourceBundleMessageSourceTests { fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode"); ms.setFileEncodings(fileCharsets); ms.setFallbackToSystemLocale(false); - try { - ms.getMessage("code1", null, Locale.ENGLISH); - fail("Should have thrown NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + ms.getMessage("code1", null, Locale.ENGLISH)); } @Test @@ -380,13 +366,8 @@ public class ResourceBundleMessageSourceTests { Properties fileCharsets = new Properties(); fileCharsets.setProperty("org/springframework/context/support/messages", "unicode"); ms.setFileEncodings(fileCharsets); - try { - ms.getMessage("code1", null, Locale.ENGLISH); - fail("Should have thrown NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // expected - } + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + ms.getMessage("code1", null, Locale.ENGLISH)); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java index 8ce3eab1d33..373194c6e51 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java @@ -153,10 +153,11 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { .equals("This is a test message in the message catalog with no args.")); } - @Test(expected = NoSuchMessageException.class) + @Test public void getMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() { // Try with Locale.US - sac.getMessage("bogus.message", null, Locale.US); + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + sac.getMessage("bogus.message", null, Locale.US)); } @Test diff --git a/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java index 71f1d0179da..1f8dd1785a3 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java @@ -27,8 +27,9 @@ import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.jndi.JndiTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -72,13 +73,9 @@ public class LocalSlsbInvokerInterceptorTests { // default resourceRef=false should cause this to fail, as java:/comp/env will not // automatically be added si.setJndiTemplate(jt); - try { - si.afterPropertiesSet(); - fail("Should have failed with naming exception"); - } - catch (NamingException ex) { - assertTrue(ex == nex); - } + assertThatExceptionOfType(NamingException.class).isThrownBy( + si::afterPropertiesSet) + .satisfies(ex -> assertThat(ex).isSameAs(nex)); } @Test @@ -136,13 +133,9 @@ public class LocalSlsbInvokerInterceptorTests { pf.addAdvice(si); LocalInterfaceWithBusinessMethods target = (LocalInterfaceWithBusinessMethods) pf.getProxy(); - try { - target.targetMethod(); - fail("Should have thrown exception"); - } - catch (Exception thrown) { - assertTrue(thrown == expected); - } + assertThatExceptionOfType(Exception.class).isThrownBy( + target::targetMethod) + .satisfies(ex -> assertThat(ex).isSameAs(expected)); verify(mockContext).close(); } diff --git a/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java index a18eac29d97..a85703e2779 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java @@ -26,10 +26,10 @@ import org.junit.Test; import org.springframework.jndi.JndiTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -139,13 +139,9 @@ public class LocalStatelessSessionProxyFactoryBeanTests { MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); assertTrue(Proxy.isProxyClass(mbm.getClass())); - try { - mbm.getValue(); - fail("Should have failed to create EJB"); - } - catch (EjbAccessException ex) { - assertSame(cex, ex.getCause()); - } + assertThatExceptionOfType(EjbAccessException.class).isThrownBy( + mbm::getValue) + .withCause(cex); } @Test @@ -174,14 +170,9 @@ public class LocalStatelessSessionProxyFactoryBeanTests { // Check it's a singleton assertTrue(fb.isSingleton()); - try { - fb.afterPropertiesSet(); - fail("Should have failed to create EJB"); - } - catch (IllegalArgumentException ex) { - // TODO more appropriate exception? - assertTrue(ex.getMessage().indexOf("businessInterface") != 1); - } + assertThatIllegalArgumentException().isThrownBy( + fb::afterPropertiesSet) + .withMessageContaining("businessInterface"); // Expect no methods on home verifyZeroInteractions(home); diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java index 9b599e0b918..68f381be589 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java @@ -30,9 +30,10 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.jndi.JndiTemplate; import org.springframework.remoting.RemoteAccessException; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -130,13 +131,9 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { // default resourceRef=false should cause this to fail, as java:/comp/env will not // automatically be added si.setJndiTemplate(jt); - try { - si.afterPropertiesSet(); - fail("Should have failed with naming exception"); - } - catch (NamingException ex) { - assertTrue(ex == nex); - } + assertThatExceptionOfType(NamingException.class).isThrownBy( + si::afterPropertiesSet) + .satisfies(ex -> assertThat(ex).isSameAs(nex)); } @Test @@ -199,13 +196,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName); RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class); - try { - target.targetMethod(); - fail("Should have thrown RemoteException"); - } - catch (RemoteException ex) { - // expected - } + assertThatExceptionOfType(RemoteException.class).isThrownBy( + target::targetMethod); verify(mockContext).close(); verify(ejb, times(2)).remove(); @@ -254,13 +246,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { si.setCacheHome(cacheHome); RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class); - try { - target.targetMethod(); - fail("Should have thrown RemoteException"); - } - catch (ConnectException ex) { - // expected - } + assertThatExceptionOfType(ConnectException.class).isThrownBy( + target::targetMethod); verify(mockContext, times(lookupCount)).close(); verify(ejb, times(2)).remove(); @@ -295,13 +282,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName); BusinessInterface target = (BusinessInterface) configuredProxy(si, BusinessInterface.class); - try { - target.targetMethod(); - fail("Should have thrown RemoteAccessException"); - } - catch (RemoteAccessException ex) { - // expected - } + assertThatExceptionOfType(RemoteAccessException.class).isThrownBy( + target::targetMethod); verify(mockContext).close(); verify(ejb).remove(); @@ -327,14 +309,9 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName); RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class); - try { - target.targetMethod(); - fail("Should have thrown remote exception"); - } - catch (Exception thrown) { - assertTrue(thrown == expected); - } - + assertThatExceptionOfType(Exception.class).isThrownBy( + target::targetMethod) + .satisfies(ex -> assertThat(ex).isSameAs(expected)); verify(mockContext).close(); verify(ejb).remove(); } diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java index 43793c38a30..6b967561250 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java @@ -28,10 +28,11 @@ import org.junit.Test; import org.springframework.jndi.JndiTemplate; import org.springframework.remoting.RemoteAccessException; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -157,13 +158,9 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); assertTrue(Proxy.isProxyClass(mbm.getClass())); - try { - mbm.getValue(); - fail("Should've thrown remote exception"); - } - catch (RemoteException ex) { - assertSame("Threw expected RemoteException", rex, ex); - } + assertThatExceptionOfType(RemoteException.class).isThrownBy( + mbm::getValue) + .satisfies(ex -> assertThat(ex).isSameAs(rex)); verify(myEjb).remove(); } @@ -196,14 +193,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); assertTrue(Proxy.isProxyClass(mbm.getClass())); - - try { - mbm.getValue(); - fail("Should have failed to create EJB"); - } - catch (RemoteException ex) { - // expected - } + assertThatExceptionOfType(RemoteException.class).isThrownBy(mbm::getValue); } @Test @@ -235,14 +225,9 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem MyLocalBusinessMethods mbm = (MyLocalBusinessMethods) fb.getObject(); assertTrue(Proxy.isProxyClass(mbm.getClass())); - - try { - mbm.getValue(); - fail("Should have failed to create EJB"); - } - catch (RemoteAccessException ex) { - assertTrue(ex.getCause() == cex); - } + assertThatExceptionOfType(RemoteAccessException.class).isThrownBy( + mbm::getValue) + .withCause(cex); } @Test @@ -271,14 +256,9 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem // Check it's a singleton assertTrue(fb.isSingleton()); - try { - fb.afterPropertiesSet(); - fail("Should have failed to create EJB"); - } - catch (IllegalArgumentException ex) { - // TODO more appropriate exception? - assertTrue(ex.getMessage().indexOf("businessInterface") != 1); - } + assertThatIllegalArgumentException().isThrownBy( + fb::afterPropertiesSet) + .withMessageContaining("businessInterface"); // Expect no methods on home verifyZeroInteractions(home); diff --git a/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java b/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java index de8ccd5055d..35f4825e103 100644 --- a/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java @@ -23,6 +23,7 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -43,9 +44,10 @@ public class CurrencyStyleFormatterTests { assertEquals(new BigDecimal("23.56"), formatter.parse("$23.56", Locale.US)); } - @Test(expected = ParseException.class) + @Test public void parseBogusValue() throws ParseException { - formatter.parse("bogus", Locale.US); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + formatter.parse("bogus", Locale.US)); } @Test @@ -59,9 +61,10 @@ public class CurrencyStyleFormatterTests { assertEquals(new BigDecimal("23.00"), formatter.parse("$23", Locale.US)); } - @Test(expected = ParseException.class) + @Test public void parseValueNotLenientFailure() throws ParseException { - formatter.parse("$23.56bogus", Locale.US); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + formatter.parse("$23.56bogus", Locale.US)); } } diff --git a/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java b/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java index 156b4a52595..9981601d54a 100644 --- a/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java @@ -22,6 +22,7 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -42,14 +43,16 @@ public class NumberStyleFormatterTests { assertEquals(new BigDecimal("23.56"), formatter.parse("23.56", Locale.US)); } - @Test(expected = ParseException.class) + @Test public void parseBogusValue() throws ParseException { - formatter.parse("bogus", Locale.US); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + formatter.parse("bogus", Locale.US)); } - @Test(expected = ParseException.class) + @Test public void parsePercentValueNotLenientFailure() throws ParseException { - formatter.parse("23.56bogus", Locale.US); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + formatter.parse("23.56bogus", Locale.US)); } } diff --git a/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java b/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java index 3caa1c9bc06..70eca26a3b6 100644 --- a/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java @@ -22,6 +22,7 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -42,14 +43,16 @@ public class PercentStyleFormatterTests { assertEquals(new BigDecimal(".2356"), formatter.parse("23.56%", Locale.US)); } - @Test(expected = ParseException.class) + @Test public void parseBogusValue() throws ParseException { - formatter.parse("bogus", Locale.US); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + formatter.parse("bogus", Locale.US)); } - @Test(expected = ParseException.class) + @Test public void parsePercentValueNotLenientFailure() throws ParseException { - formatter.parse("23.56%bogus", Locale.US); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + formatter.parse("23.56%bogus", Locale.US)); } } diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java index 6b652379ccd..40d62e179d8 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java @@ -39,9 +39,9 @@ import org.springframework.format.Parser; import org.springframework.format.Printer; import org.springframework.format.annotation.NumberFormat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rossen Stoyanchev @@ -76,13 +76,9 @@ public class FormattingConversionServiceFactoryBeanTests { FormattingConversionService fcs = factory.getObject(); TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern")); - try { - fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor); - fail("This format should not be parseable"); - } - catch (ConversionFailedException ex) { - assertTrue(ex.getCause() instanceof NumberFormatException); - } + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor)) + .withCauseInstanceOf(NumberFormatException.class); } @Test @@ -126,13 +122,7 @@ public class FormattingConversionServiceFactoryBeanTests { Set formatters = new HashSet<>(); formatters.add(new Object()); factory.setFormatters(formatters); - try { - factory.afterPropertiesSet(); - fail("Expected formatter to be rejected"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(factory::afterPropertiesSet); } diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java index 7ac4e3f0a6a..27b19bafbd1 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java @@ -55,6 +55,7 @@ import org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationForm import org.springframework.format.datetime.joda.ReadablePartialPrinter; import org.springframework.format.number.NumberStyleFormatter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -265,16 +266,18 @@ public class FormattingConversionServiceTests { assertNull(formattingService.convert(" ", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); } - @Test(expected = ConversionFailedException.class) + @Test public void parseParserReturnsNull() throws ParseException { formattingService.addFormatterForFieldType(Integer.class, new NullReturningFormatter()); - assertNull(formattingService.convert("1", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + formattingService.convert("1", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); } - @Test(expected = ConversionFailedException.class) + @Test public void parseNullPrimitiveProperty() throws ParseException { formattingService.addFormatterForFieldType(Integer.class, new NumberStyleFormatter()); - assertNull(formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class))); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class))); } @Test diff --git a/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java b/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java index 5ae01d06a34..b4a91764dd3 100644 --- a/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java +++ b/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java @@ -21,6 +21,8 @@ import java.security.ProtectionDomain; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -32,14 +34,16 @@ import static org.junit.Assert.assertNotNull; */ public class ReflectiveLoadTimeWeaverTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullClassLoader() { - new ReflectiveLoadTimeWeaver(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ReflectiveLoadTimeWeaver(null)); } - @Test(expected = IllegalStateException.class) + @Test public void testCtorWithClassLoaderThatDoesNotExposeAnAddTransformerMethod() { - new ReflectiveLoadTimeWeaver(getClass().getClassLoader()); + assertThatIllegalStateException().isThrownBy(() -> + new ReflectiveLoadTimeWeaver(getClass().getClassLoader())); } @Test @@ -55,9 +59,10 @@ public class ReflectiveLoadTimeWeaverTests { assertEquals(1, classLoader.getNumTimesGetThrowawayClassLoaderCalled()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddTransformerWithNullTransformer() { - new ReflectiveLoadTimeWeaver(new JustAddTransformerClassLoader()).addTransformer(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ReflectiveLoadTimeWeaver(new JustAddTransformerClassLoader()).addTransformer(null)); } @Test diff --git a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java index 3d664697682..74ba772e17f 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java @@ -17,7 +17,6 @@ package org.springframework.jmx.access; import java.beans.PropertyDescriptor; -import java.io.IOException; import java.lang.reflect.Method; import java.net.BindException; import java.util.HashMap; @@ -38,6 +37,9 @@ import org.springframework.jmx.export.MBeanExporter; import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssembler; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIOException; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; @@ -119,32 +121,36 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The name of the bean should have been updated", "Rob Harrop", target.getName()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetAttributeValueWithRuntimeException() throws Exception { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); - proxy.setName("Juergen"); + assertThatIllegalArgumentException().isThrownBy(() -> + proxy.setName("Juergen")); } - @Test(expected = ClassNotFoundException.class) + @Test public void testSetAttributeValueWithCheckedException() throws Exception { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); - proxy.setName("Juergen Class"); + assertThatExceptionOfType(ClassNotFoundException.class).isThrownBy(() -> + proxy.setName("Juergen Class")); } - @Test(expected = IOException.class) + @Test public void testSetAttributeValueWithIOException() throws Exception { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); - proxy.setName("Juergen IO"); + assertThatIOException().isThrownBy(() -> + proxy.setName("Juergen IO")); } - @Test(expected = InvalidInvocationException.class) + @Test public void testSetReadOnlyAttribute() throws Exception { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); - proxy.setAge(900); + assertThatExceptionOfType(InvalidInvocationException.class).isThrownBy(() -> + proxy.setAge(900)); } @Test @@ -163,11 +169,12 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The operation should return 3", 3, result); } - @Test(expected = InvalidInvocationException.class) + @Test public void testInvokeUnexposedMethodWithException() throws Exception { assumeTrue(runTests); IJmxTestBean bean = getProxy(); - bean.dontExposeMe(); + assertThatExceptionOfType(InvalidInvocationException.class).isThrownBy(() -> + bean.dontExposeMe()); } @Test diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java index b526993ece6..2c6eca07e33 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java @@ -30,8 +30,8 @@ import org.springframework.jmx.JmxTestBean; import org.springframework.jmx.export.naming.ObjectNamingStrategy; import org.springframework.jmx.support.ObjectNameManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -114,13 +114,9 @@ public class MBeanExporterOperationsTests extends AbstractMBeanServerTests { ObjectName reg1 = exporter.registerManagedResource(bean1); assertIsRegistered("Bean 1 not registered with MBeanServer", reg1); - try { - exporter.registerManagedResource(bean2); - fail("Shouldn't be able to register a runtime MBean with a reused ObjectName."); - } - catch (MBeanExportException e) { - assertEquals("Incorrect root cause", InstanceAlreadyExistsException.class, e.getCause().getClass()); - } + assertThatExceptionOfType(MBeanExportException.class).isThrownBy(()-> + exporter.registerManagedResource(bean2)) + .withCauseExactlyInstanceOf(InstanceAlreadyExistsException.class); } private void assertObjectNameMatchesTemplate(ObjectName objectNameTemplate, ObjectName registeredName) { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index f09a0dcbabe..8f8321ed59d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -55,13 +55,12 @@ import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Integration tests for the {@link MBeanExporter} class. @@ -105,14 +104,9 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { exporter.setBeans(getBeanMap()); exporter.setServer(server); exporter.setNotificationListenerMappings(listeners); - try { - start(exporter); - fail("Must have thrown an MBeanExportException when registering a " + - "NotificationListener on a non-existent MBean."); - } - catch (MBeanExportException expected) { - assertTrue(expected.contains(InstanceNotFoundException.class)); - } + assertThatExceptionOfType(MBeanExportException.class).as("NotificationListener on a non-existent MBean").isThrownBy(() -> + start(exporter)) + .satisfies(ex -> assertThat(ex.contains(InstanceNotFoundException.class))); } @Test @@ -617,12 +611,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { exporter.setBeans(beansToExport); exporter.setBeanFactory(factory); - try { - start(exporter); - fail("Must have failed during creation of RuntimeExceptionThrowingConstructorBean"); - } - catch (RuntimeException expected) { - } + assertThatExceptionOfType(RuntimeException.class).as("failed during creation of RuntimeExceptionThrowingConstructorBean").isThrownBy(() -> + start(exporter)); assertIsNotRegistered("Must have unregistered all previously registered MBeans due to RuntimeException", ObjectNameManager.getInstance(objectName1)); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java index 4d1a8fe7d3b..486571d0f75 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java @@ -35,8 +35,8 @@ import org.springframework.jmx.access.NotificationListenerRegistrar; import org.springframework.jmx.export.naming.SelfNaming; import org.springframework.jmx.support.ObjectNameManager; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -199,12 +199,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { @Test public void testCreationWithNoNotificationListenerSet() { - try { - new NotificationListenerBean().afterPropertiesSet(); - fail("Must have thrown an IllegalArgumentException (no NotificationListener supplied)"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().as("no NotificationListener supplied").isThrownBy( + new NotificationListenerBean()::afterPropertiesSet); } @SuppressWarnings({ "rawtypes", "unchecked" }) diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java index 4b360d22273..f5e50bde8af 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java @@ -23,10 +23,10 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -47,24 +47,14 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse @Test public void testWithUnknownClass() throws Exception { - try { - getWithMapping("com.foo.bar.Unknown"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + getWithMapping("com.foo.bar.Unknown")); } @Test public void testWithNonInterface() throws Exception { - try { - getWithMapping("JmxTestBean"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + getWithMapping("JmxTestBean")); } @Test diff --git a/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java b/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java index bd095bd2a88..79fa59a9be8 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import org.springframework.jmx.export.SpringModelMBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -37,26 +38,30 @@ import static org.junit.Assert.assertTrue; */ public class ModelMBeanNotificationPublisherTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullMBean() throws Exception { - new ModelMBeanNotificationPublisher(null, createObjectName(), this); + assertThatIllegalArgumentException().isThrownBy(() -> + new ModelMBeanNotificationPublisher(null, createObjectName(), this)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullObjectName() throws Exception { - new ModelMBeanNotificationPublisher(new SpringModelMBean(), null, this); + assertThatIllegalArgumentException().isThrownBy(() -> + new ModelMBeanNotificationPublisher(new SpringModelMBean(), null, this)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCtorWithNullManagedResource() throws Exception { - new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSendNullNotification() throws Exception { NotificationPublisher publisher = new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), this); - publisher.sendNotification(null); + assertThatIllegalArgumentException().isThrownBy(() -> + publisher.sendNotification(null)); } public void testSendVanillaNotification() throws Exception { diff --git a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java index 0776c86799d..0cda82b944f 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java @@ -31,9 +31,9 @@ import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -99,14 +99,10 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { public void noRegisterWithMBeanServer() throws Exception { ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean(); bean.afterPropertiesSet(); - try { // Try to get the connector bean. - getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME)); - fail("Instance should not be found"); - } - catch (InstanceNotFoundException ex) { - // expected + assertThatExceptionOfType(InstanceNotFoundException.class).isThrownBy(() -> + getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME))); } finally { bean.destroy(); diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java index d220cf43c94..7639e404c9d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java @@ -28,6 +28,7 @@ import org.springframework.aop.support.AopUtils; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -76,10 +77,11 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } - @Test(expected = IllegalArgumentException.class) + @Test public void testWithNoServiceUrl() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); - bean.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + bean::afterPropertiesSet); } @Test diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java index 811c97a4baa..c2a5cfbe068 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java @@ -27,10 +27,10 @@ import org.junit.Test; import org.springframework.util.MBeanTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -138,26 +138,23 @@ public class MBeanServerFactoryBeanTests { MBeanServerFactoryBean bean = new MBeanServerFactoryBean(); bean.setRegisterWithFactory(referenceShouldExist); bean.afterPropertiesSet(); - try { MBeanServer server = bean.getObject(); List servers = MBeanServerFactory.findMBeanServer(null); - - boolean found = false; - for (MBeanServer candidate : servers) { - if (candidate == server) { - found = true; - break; - } - } - - if (!(found == referenceShouldExist)) { - fail(failMsg); - } + assertThat(hasInstance(servers, server)).as(failMsg).isEqualTo(referenceShouldExist); } finally { bean.destroy(); } } + private boolean hasInstance(List servers, MBeanServer server) { + for (MBeanServer candidate : servers) { + if (candidate == server) { + return true; + } + } + return false; + } + } diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java index a635a4a1892..632764ffd13 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java @@ -27,10 +27,12 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -46,12 +48,7 @@ public class JndiObjectFactoryBeanTests { @Test public void testNoJndiName() throws NamingException { JndiObjectFactoryBean jof = new JndiObjectFactoryBean(); - try { - jof.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - } + assertThatIllegalArgumentException().isThrownBy(jof::afterPropertiesSet); } @Test @@ -116,13 +113,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiTemplate(new ExpectedLookupTemplate("java:comp/env/foo", o)); jof.setJndiName("foo"); jof.setResourceRef(false); - try { - jof.afterPropertiesSet(); - fail("Should have thrown NamingException"); - } - catch (NamingException ex) { - // expected - } + assertThatExceptionOfType(NamingException.class).isThrownBy(jof::afterPropertiesSet); } @Test @@ -153,13 +144,9 @@ public class JndiObjectFactoryBeanTests { jof.setJndiTemplate(new ExpectedLookupTemplate("foo", new Object())); jof.setJndiName("foo"); jof.setExpectedType(String.class); - try { - jof.afterPropertiesSet(); - fail("Should have thrown NamingException"); - } - catch (NamingException ex) { - assertTrue(ex.getMessage().contains("java.lang.String")); - } + assertThatExceptionOfType(NamingException.class).isThrownBy( + jof::afterPropertiesSet) + .withMessageContaining("java.lang.String"); } @Test @@ -214,13 +201,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("myFoo"); jof.setExpectedType(Boolean.class); jof.setDefaultObject("5"); - try { - jof.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(jof::afterPropertiesSet); } @Test @@ -246,13 +227,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("myFoo"); jof.setProxyInterface(ITestBean.class); jof.setDefaultObject(Boolean.TRUE); - try { - jof.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(jof::afterPropertiesSet); } @Test @@ -349,13 +324,7 @@ public class JndiObjectFactoryBeanTests { JndiObjectFactoryBean jof = new JndiObjectFactoryBean(); jof.setJndiName("foo"); jof.setLookupOnStartup(false); - try { - jof.afterPropertiesSet(); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(jof::afterPropertiesSet); } @Test @@ -364,13 +333,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setCache(false); jof.setLookupOnStartup(false); - try { - jof.afterPropertiesSet(); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(jof::afterPropertiesSet); } @Test @@ -397,13 +360,9 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setExpectedType(DerivedTestBean.class); jof.setProxyInterface(ITestBean.class); - try { - jof.afterPropertiesSet(); - fail("Should have thrown NamingException"); - } - catch (NamingException ex) { - assertTrue(ex.getMessage().contains("org.springframework.tests.sample.beans.DerivedTestBean")); - } + assertThatExceptionOfType(NamingException.class).isThrownBy( + jof::afterPropertiesSet) + .withMessageContaining("org.springframework.tests.sample.beans.DerivedTestBean"); } @Test diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java index c5ead5a9724..376f91ca30b 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java @@ -18,8 +18,8 @@ package org.springframework.jndi; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -29,13 +29,8 @@ public class JndiTemplateEditorTests { @Test public void testNullIsIllegalArgument() { - try { - new JndiTemplateEditor().setAsText(null); - fail("Null is illegal"); - } - catch (IllegalArgumentException ex) { - // OK - } + assertThatIllegalArgumentException().isThrownBy(() -> + new JndiTemplateEditor().setAsText(null)); } @Test diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java index 58be8bc5685..163ca418061 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java @@ -21,8 +21,8 @@ import javax.naming.NameNotFoundException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -68,13 +68,8 @@ public class JndiTemplateTests { } }; - try { - jt.lookup(name); - fail("Should have thrown NamingException"); - } - catch (NameNotFoundException ex) { - // Ok - } + assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> + jt.lookup(name)); verify(context).close(); } @@ -91,13 +86,8 @@ public class JndiTemplateTests { } }; - try { - jt.lookup(name); - fail("Should have thrown NamingException"); - } - catch (NameNotFoundException ex) { - // Ok - } + assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> + jt.lookup(name)); verify(context).close(); } @@ -115,13 +105,8 @@ public class JndiTemplateTests { } }; - try { - jt.lookup(name, String.class); - fail("Should have thrown TypeMismatchNamingException"); - } - catch (TypeMismatchNamingException ex) { - // Ok - } + assertThatExceptionOfType(TypeMismatchNamingException.class).isThrownBy(() -> + jt.lookup(name, String.class)); verify(context).close(); } diff --git a/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java b/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java index c672128c591..7f7c297b2a6 100644 --- a/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java @@ -38,9 +38,9 @@ import org.junit.Test; import org.springframework.tests.mock.jndi.SimpleNamingContext; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -86,35 +86,20 @@ public class SimpleNamingContextTests { assertTrue("key1 removed", context3.getEnvironment().get("key1") == null); assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds); - try { - context1.lookup("myobject"); - fail("Should have thrown NameNotFoundException"); - } - catch (NameNotFoundException ex) { - // expected - } + assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> + context1.lookup("myobject")); assertTrue("Correct Integer registered", context1.lookup("myinteger") == i); assertTrue("Correct String registered", context1.lookup("mystring") == s); assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds); - try { - context2.lookup("myobject"); - fail("Should have thrown NameNotFoundException"); - } - catch (NameNotFoundException ex) { - // expected - } + assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> + context2.lookup("myobject")); assertTrue("Correct Integer registered", context2.lookup("myinteger") == i); assertTrue("Correct String registered", context2.lookup("mystring") == s); assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds); - try { - context3.lookup("myobject"); - fail("Should have thrown NameNotFoundException"); - } - catch (NameNotFoundException ex) { - // expected - } + assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> + context3.lookup("myobject")); assertTrue("Correct Integer registered", context3.lookup("myinteger") == i); assertTrue("Correct String registered", context3.lookup("mystring") == s); @@ -192,28 +177,18 @@ public class SimpleNamingContextTests { assertTrue(ctx.lookup(name) == o); // Check it returns mutable contexts ctx.unbind(name); - try { - ctx = new InitialContext(); - ctx.lookup(name); - fail("Should have thrown NamingException"); - } - catch (NamingException ex) { - // expected - } + InitialContext badCtx1 = new InitialContext(); + assertThatExceptionOfType(NamingException.class).isThrownBy(() -> + badCtx1.lookup(name)); // Check the same call will work again, but the context is empty builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder(); - try { - ctx = new InitialContext(); - ctx.lookup(name); - fail("Should have thrown NamingException"); - } - catch (NamingException ex) { - // expected - } + InitialContext badCtx2 = new InitialContext(); + assertThatExceptionOfType(NamingException.class).isThrownBy(() -> + badCtx2.lookup(name)); Object o2 = new Object(); builder.bind(name, o2); - assertEquals(ctx.lookup(name), o2); + assertEquals(badCtx2.lookup(name), o2); } diff --git a/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java b/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java index 7dcea16635e..8ec2b4b54ed 100644 --- a/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java +++ b/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java @@ -37,10 +37,12 @@ import org.springframework.remoting.RemoteConnectFailureException; import org.springframework.remoting.RemoteProxyFailureException; import org.springframework.remoting.support.RemoteInvocation; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -102,25 +104,15 @@ public class RmiSupportTests { doTestRmiProxyFactoryBeanWithException(UnmarshalException.class); } - private void doTestRmiProxyFactoryBeanWithException(Class exceptionClass) throws Exception { + private void doTestRmiProxyFactoryBeanWithException(Class exceptionClass) throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IRemoteBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); factory.afterPropertiesSet(); assertTrue(factory.getObject() instanceof IRemoteBean); IRemoteBean proxy = (IRemoteBean) factory.getObject(); - try { - proxy.setName(exceptionClass.getName()); - fail("Should have thrown " + exceptionClass.getName()); - } - catch (Exception ex) { - if (exceptionClass.isInstance(ex)) { - // expected - } - else { - throw ex; - } - } + assertThatExceptionOfType(exceptionClass).isThrownBy(() -> + proxy.setName(exceptionClass.getName())); assertEquals(1, factory.counter); } @@ -149,7 +141,7 @@ public class RmiSupportTests { doTestRmiProxyFactoryBeanWithExceptionAndRefresh(StubNotFoundException.class); } - private void doTestRmiProxyFactoryBeanWithExceptionAndRefresh(Class exceptionClass) throws Exception { + private void doTestRmiProxyFactoryBeanWithExceptionAndRefresh(Class exceptionClass) throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IRemoteBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); @@ -157,18 +149,8 @@ public class RmiSupportTests { factory.afterPropertiesSet(); assertTrue(factory.getObject() instanceof IRemoteBean); IRemoteBean proxy = (IRemoteBean) factory.getObject(); - try { - proxy.setName(exceptionClass.getName()); - fail("Should have thrown " + exceptionClass.getName()); - } - catch (Exception ex) { - if (exceptionClass.isInstance(ex)) { - // expected - } - else { - throw ex; - } - } + assertThatExceptionOfType(exceptionClass).isThrownBy(() -> + proxy.setName(exceptionClass.getName())); assertEquals(2, factory.counter); } @@ -195,15 +177,11 @@ public class RmiSupportTests { assertTrue(factory.getObject() instanceof IWrongBusinessBean); IWrongBusinessBean proxy = (IWrongBusinessBean) factory.getObject(); assertFalse(proxy instanceof IRemoteBean); - try { - proxy.setOtherName("name"); - fail("Should have thrown RemoteProxyFailureException"); - } - catch (RemoteProxyFailureException ex) { - assertTrue(ex.getCause() instanceof NoSuchMethodException); - assertTrue(ex.getMessage().contains("setOtherName")); - assertTrue(ex.getMessage().contains("IWrongBusinessBean")); - } + assertThatExceptionOfType(RemoteProxyFailureException.class).isThrownBy(() -> + proxy.setOtherName("name")) + .withCauseInstanceOf(NoSuchMethodException.class) + .withMessageContaining("setOtherName") + .withMessageContaining("IWrongBusinessBean"); assertEquals(1, factory.counter); } @@ -244,7 +222,7 @@ public class RmiSupportTests { } private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( - Class rmiExceptionClass, Class springExceptionClass) throws Exception { + Class rmiExceptionClass, Class springExceptionClass) throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IBusinessBean.class); @@ -253,18 +231,8 @@ public class RmiSupportTests { assertTrue(factory.getObject() instanceof IBusinessBean); IBusinessBean proxy = (IBusinessBean) factory.getObject(); assertFalse(proxy instanceof IRemoteBean); - try { - proxy.setName(rmiExceptionClass.getName()); - fail("Should have thrown " + rmiExceptionClass.getName()); - } - catch (Exception ex) { - if (springExceptionClass.isInstance(ex)) { - // expected - } - else { - throw ex; - } - } + assertThatExceptionOfType(springExceptionClass).isThrownBy(() -> + proxy.setName(rmiExceptionClass.getName())); assertEquals(1, factory.counter); } @@ -305,7 +273,7 @@ public class RmiSupportTests { } private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( - Class rmiExceptionClass, Class springExceptionClass) throws Exception { + Class rmiExceptionClass, Class springExceptionClass) throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IBusinessBean.class); @@ -315,38 +283,17 @@ public class RmiSupportTests { assertTrue(factory.getObject() instanceof IBusinessBean); IBusinessBean proxy = (IBusinessBean) factory.getObject(); assertFalse(proxy instanceof IRemoteBean); - try { - proxy.setName(rmiExceptionClass.getName()); - fail("Should have thrown " + rmiExceptionClass.getName()); - } - catch (Exception ex) { - if (springExceptionClass.isInstance(ex)) { - // expected - } - else { - throw ex; - } - } - if (RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass)) { - assertEquals(2, factory.counter); - } - else { - assertEquals(1, factory.counter); - } + assertThatExceptionOfType(springExceptionClass).isThrownBy(() -> + proxy.setName(rmiExceptionClass.getName())); + boolean isRemoteConnectFaiure = RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass); + assertThat(factory.counter).isEqualTo(isRemoteConnectFaiure ? 2 : 1); } @Test public void rmiClientInterceptorRequiresUrl() throws Exception{ RmiClientInterceptor client = new RmiClientInterceptor(); client.setServiceInterface(IRemoteBean.class); - - try { - client.afterPropertiesSet(); - fail("url isn't set, expected IllegalArgumentException"); - } - catch (IllegalArgumentException ex){ - // expected - } + assertThatIllegalArgumentException().isThrownBy(client::afterPropertiesSet); } @Test @@ -430,13 +377,8 @@ public class RmiSupportTests { assertTrue(proxy.equals(proxy)); // should go through - try { - proxy.setName("test"); - fail("Should have thrown RemoteAccessException"); - } - catch (RemoteAccessException ex) { - // expected - } + assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> + proxy.setName("test")); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java index c09aa811cc3..5320741f45a 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java @@ -42,11 +42,10 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.ReflectionUtils; import org.springframework.util.concurrent.ListenableFuture; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Mark Fisher @@ -220,17 +219,9 @@ public class AsyncAnnotationBeanPostProcessorTests { private void assertFutureWithException(Future result, TestableAsyncUncaughtExceptionHandler exceptionHandler) { - - try { - result.get(); - } - catch (InterruptedException ex) { - fail("Should not have failed with InterruptedException: " + ex); - } - catch (ExecutionException ex) { - // expected - assertEquals("Wrong exception cause", UnsupportedOperationException.class, ex.getCause().getClass()); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + result::get) + .withCauseExactlyInstanceOf(UnsupportedOperationException.class); assertFalse("handler should never be called with Future return type", exceptionHandler.isCalled()); } @@ -264,13 +255,8 @@ public class AsyncAnnotationBeanPostProcessorTests { ITestBean testBean = context.getBean("target", ITestBean.class); assertFalse("Handler should not have been called", exceptionHandler.isCalled()); - try { - testBean.failWithVoid(); - exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); - } - catch (Exception e) { - fail("No unexpected exception should have been received"); - } + testBean.failWithVoid(); + exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); } private ConfigurableApplicationContext initContext(BeanDefinition asyncAnnotationBeanPostProcessorDefinition) { diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java index 9378b611191..64e6c2149c0 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java @@ -43,9 +43,9 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.concurrent.ListenableFuture; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -80,45 +80,25 @@ public class AsyncExecutionTests { CompletableFuture completableFuture = asyncTest.returnSomethingCompletable(20); assertEquals("20", completableFuture.get()); - try { - asyncTest.returnSomething(0).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomething(0).get()) + .withCauseInstanceOf(IllegalArgumentException.class); - try { - asyncTest.returnSomething(-1).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IOException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomething(-1).get()) + .withCauseInstanceOf(IOException.class); - try { - asyncTest.returnSomethingListenable(0).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomethingListenable(0).get()) + .withCauseInstanceOf(IllegalArgumentException.class); - try { - asyncTest.returnSomethingListenable(-1).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IOException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomethingListenable(-1).get()) + .withCauseInstanceOf(IOException.class); - try { - asyncTest.returnSomethingCompletable(0).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomethingCompletable(0).get()) + .withCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -197,29 +177,17 @@ public class AsyncExecutionTests { CompletableFuture completableFuture = asyncTest.returnSomethingCompletable(20); assertEquals("20", completableFuture.get()); - try { - asyncTest.returnSomething(0).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomething(0).get()) + .withCauseInstanceOf(IllegalArgumentException.class); - try { - asyncTest.returnSomethingListenable(0).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomethingListenable(0).get()) + .withCauseInstanceOf(IllegalArgumentException.class); - try { - asyncTest.returnSomethingCompletable(0).get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + asyncTest.returnSomethingCompletable(0).get()) + .withCauseInstanceOf(IllegalArgumentException.class); } @Test diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java index 3d0a1d4c204..6fe92288603 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java @@ -26,8 +26,8 @@ import org.junit.Test; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -46,7 +46,7 @@ public class AsyncResultTests { } @Override public void onFailure(Throwable ex) { - fail("Failure callback not expected: " + ex); + throw new AssertionError("Failure callback not expected: " + ex, ex); } }); assertSame(value, values.iterator().next()); @@ -63,7 +63,7 @@ public class AsyncResultTests { future.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(String result) { - fail("Success callback not expected: " + result); + throw new AssertionError("Success callback not expected: " + result); } @Override public void onFailure(Throwable ex) { @@ -71,20 +71,12 @@ public class AsyncResultTests { } }); assertSame(ex, values.iterator().next()); - try { - future.get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex2) { - assertSame(ex, ex2.getCause()); - } - try { - future.completable().get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex2) { - assertSame(ex, ex2.getCause()); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + future::get) + .withCause(ex); + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + future.completable()::get) + .withCause(ex); } @Test @@ -92,7 +84,7 @@ public class AsyncResultTests { String value = "val"; final Set values = new HashSet<>(1); ListenableFuture future = AsyncResult.forValue(value); - future.addCallback(values::add, ex -> fail("Failure callback not expected: " + ex)); + future.addCallback(values::add, ex -> new AssertionError("Failure callback not expected: " + ex)); assertSame(value, values.iterator().next()); assertSame(value, future.get()); assertSame(value, future.completable().get()); @@ -104,22 +96,14 @@ public class AsyncResultTests { IOException ex = new IOException(); final Set values = new HashSet<>(1); ListenableFuture future = AsyncResult.forExecutionException(ex); - future.addCallback(result -> fail("Success callback not expected: " + result), values::add); + future.addCallback(result -> new AssertionError("Success callback not expected: " + result), values::add); assertSame(ex, values.iterator().next()); - try { - future.get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex2) { - assertSame(ex, ex2.getCause()); - } - try { - future.completable().get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex2) { - assertSame(ex, ex2.getCause()); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + future::get) + .withCause(ex); + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + future.completable()::get) + .withCause(ex); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java index 964537093ef..b8bb9014f21 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,15 +54,14 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; +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.instanceOf; 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; -import static org.junit.Assert.fail; /** * Tests use of @EnableAsync on @Configuration classes. @@ -102,14 +101,9 @@ public class EnableAsyncTests { public void properExceptionForExistingProxyDependencyMismatch() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AsyncConfig.class, AsyncBeanWithInterface.class, AsyncBeanUser.class); - - try { - ctx.refresh(); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException); - } + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + ctx::refresh) + .withCauseInstanceOf(BeanNotOfRequiredTypeException.class); ctx.close(); } @@ -117,15 +111,9 @@ public class EnableAsyncTests { public void properExceptionForResolvedProxyDependencyMismatch() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AsyncConfig.class, AsyncBeanUser.class, AsyncBeanWithInterface.class); - - try { - ctx.refresh(); - fail("Should have thrown UnsatisfiedDependencyException"); - } - catch (UnsatisfiedDependencyException ex) { - assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException); - } - + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy( + ctx::refresh) + .withCauseInstanceOf(BeanNotOfRequiredTypeException.class); ctx.close(); } @@ -195,12 +183,13 @@ public class EnableAsyncTests { /** * Fails with classpath errors on trying to classload AnnotationAsyncExecutionAspect. */ - @Test(expected = BeanDefinitionStoreException.class) + @Test public void aspectModeAspectJAttemptsToRegisterAsyncAspect() { @SuppressWarnings("resource") AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AspectJAsyncAnnotationConfig.class); - ctx.refresh(); + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy( + ctx::refresh); } @Test @@ -334,17 +323,9 @@ public class EnableAsyncTests { @Test @SuppressWarnings("resource") public void exceptionThrownWithBeanNotOfRequiredTypeRootCause() { - try { - new AnnotationConfigApplicationContext(JdkProxyConfiguration.class); - fail("Should have thrown exception"); - } - catch (Throwable ex) { - ex.printStackTrace(); - while (ex.getCause() != null) { - ex = ex.getCause(); - } - assertThat(ex, instanceOf(BeanNotOfRequiredTypeException.class)); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + new AnnotationConfigApplicationContext(JdkProxyConfiguration.class)) + .withCauseInstanceOf(BeanNotOfRequiredTypeException.class); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java index 4c2b11f0562..c4c5f113bb6 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java @@ -58,6 +58,7 @@ import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -306,16 +307,17 @@ public class ScheduledAnnotationBeanPostProcessorTests { assertEquals(cal.getTime(), nextExecutionTime); // assert that 6:00 is next execution time } - @Test(expected = BeanCreationException.class) + @Test public void cronTaskWithInvalidZone() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(CronWithInvalidTimezoneTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); - context.refresh(); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh); } - @Test(expected = BeanCreationException.class) + @Test public void cronTaskWithMethodValidation() { BeanDefinition validationDefinition = new RootBeanDefinition(MethodValidationPostProcessor.class); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); @@ -323,7 +325,8 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.registerBeanDefinition("methodValidation", validationDefinition); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); - context.refresh(); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh); } @Test @@ -661,31 +664,34 @@ public class ScheduledAnnotationBeanPostProcessorTests { assertEquals("0 0 9-17 * * MON-FRI", task.getExpression()); } - @Test(expected = BeanCreationException.class) + @Test public void emptyAnnotation() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(EmptyAnnotationTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); - context.refresh(); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh); } - @Test(expected = BeanCreationException.class) + @Test public void invalidCron() throws Throwable { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(InvalidCronTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); - context.refresh(); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh); } - @Test(expected = BeanCreationException.class) + @Test public void nonEmptyParamList() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(NonEmptyParamListTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); - context.refresh(); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + context::refresh); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java index 390a349380d..5ab755704c4 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java @@ -33,6 +33,7 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.core.task.AsyncListenableTaskExecutor; import org.springframework.util.concurrent.ListenableFuture; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -90,28 +91,26 @@ public abstract class AbstractSchedulingTaskExecutorTests { assertThreadNamePrefix(task); } - @Test(expected = ExecutionException.class) + @Test public void submitFailingRunnable() throws Exception { TestTask task = new TestTask(0); Future future = executor.submit(task); - try { - future.get(1000, TimeUnit.MILLISECONDS); - } - catch (ExecutionException ex) { - assertTrue(future.isDone()); - throw ex; - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + future.get(1000, TimeUnit.MILLISECONDS)); + assertTrue(future.isDone()); } - @Test(expected = CancellationException.class) + @Test public void submitRunnableWithGetAfterShutdown() throws Exception { TestTask task1 = new TestTask(-1); Future future1 = executor.submit(task1); TestTask task2 = new TestTask(-1); Future future2 = executor.submit(task2); shutdownExecutor(); - future1.get(); - future2.get(); + assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> { + future1.get(); + future2.get(); + }); } @Test @@ -143,15 +142,17 @@ public abstract class AbstractSchedulingTaskExecutorTests { assertSame(RuntimeException.class, outcome.getClass()); } - @Test(expected = CancellationException.class) + @Test public void submitListenableRunnableWithGetAfterShutdown() throws Exception { TestTask task1 = new TestTask(-1); ListenableFuture future1 = executor.submitListenable(task1); TestTask task2 = new TestTask(-1); ListenableFuture future2 = executor.submitListenable(task2); shutdownExecutor(); - future1.get(); - future2.get(); + assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> { + future1.get(); + future2.get(); + }); } @Test @@ -162,23 +163,26 @@ public abstract class AbstractSchedulingTaskExecutorTests { assertEquals(THREAD_NAME_PREFIX, result.substring(0, THREAD_NAME_PREFIX.length())); } - @Test(expected = ExecutionException.class) + @Test public void submitFailingCallable() throws Exception { TestCallable task = new TestCallable(0); Future future = executor.submit(task); - future.get(1000, TimeUnit.MILLISECONDS); + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + future.get(1000, TimeUnit.MILLISECONDS)); assertTrue(future.isDone()); } - @Test(expected = CancellationException.class) + @Test public void submitCallableWithGetAfterShutdown() throws Exception { TestCallable task1 = new TestCallable(-1); Future future1 = executor.submit(task1); TestCallable task2 = new TestCallable(-1); Future future2 = executor.submit(task2); shutdownExecutor(); - future1.get(1000, TimeUnit.MILLISECONDS); - future2.get(1000, TimeUnit.MILLISECONDS); + assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> { + future1.get(1000, TimeUnit.MILLISECONDS); + future2.get(1000, TimeUnit.MILLISECONDS); + }); } @Test @@ -210,7 +214,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { assertSame(RuntimeException.class, outcome.getClass()); } - @Test(expected = CancellationException.class) + @Test public void submitListenableCallableWithGetAfterShutdown() throws Exception { TestCallable task1 = new TestCallable(-1); ListenableFuture future1 = executor.submitListenable(task1); @@ -218,7 +222,8 @@ public abstract class AbstractSchedulingTaskExecutorTests { ListenableFuture future2 = executor.submitListenable(task2); shutdownExecutor(); future1.get(1000, TimeUnit.MILLISECONDS); - future2.get(1000, TimeUnit.MILLISECONDS); + assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> + future2.get(1000, TimeUnit.MILLISECONDS)); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java index 88b5aed7317..da2247ca894 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java @@ -27,9 +27,9 @@ import org.springframework.core.task.NoOpRunnable; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; @@ -44,17 +44,9 @@ public class ScheduledExecutorFactoryBeanTests { @Test public void testThrowsExceptionIfPoolSizeIsLessThanZero() throws Exception { - try { - ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean(); - factory.setPoolSize(-1); - factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{ - new NoOpScheduledExecutorTask() - }); - factory.afterPropertiesSet(); - fail("Pool size less than zero"); - } - catch (IllegalArgumentException expected) { - } + ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean(); + assertThatIllegalArgumentException().isThrownBy(() -> + factory.setPoolSize(-1)); } @Test diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java index 7253d70e2c9..7ee86c3d907 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java @@ -31,6 +31,7 @@ import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.util.ErrorHandler; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -98,17 +99,13 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor assertThreadNamePrefix(task); } - @Test(expected = ExecutionException.class) + @Test public void scheduleOneTimeFailingTaskWithoutErrorHandler() throws Exception { TestTask task = new TestTask(0); Future future = scheduler.schedule(task, new Date()); - try { - future.get(1000, TimeUnit.MILLISECONDS); - } - catch (ExecutionException ex) { - assertTrue(future.isDone()); - throw ex; - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> + future.get(1000, TimeUnit.MILLISECONDS)); + assertTrue(future.isDone()); } @Test diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java index 06d65944cc5..284080b5833 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java @@ -31,6 +31,7 @@ import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.CustomizableThreadCreator; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -76,9 +77,10 @@ public class ExecutorBeanDefinitionParserTests { assertEquals(42, getMaxPoolSize(executor)); } - @Test(expected = BeanCreationException.class) + @Test public void invalidPoolSize() { - this.context.getBean("invalidPoolSize"); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + this.context.getBean("invalidPoolSize")); } @Test @@ -126,9 +128,10 @@ public class ExecutorBeanDefinitionParserTests { assertEquals(true, getAllowCoreThreadTimeOut(executor)); } - @Test(expected = BeanCreationException.class) + @Test public void propertyPlaceholderWithInvalidPoolSize() { - this.context.getBean("propertyPlaceholderWithInvalidPoolSize"); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + this.context.getBean("propertyPlaceholderWithInvalidPoolSize")); } @Test diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java index 315b24f3965..500b04519ad 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java @@ -20,6 +20,7 @@ import java.util.Date; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -49,24 +50,28 @@ public class CronSequenceGeneratorTests { new CronSequenceGenerator("0 */2 1-4 * * *").next(new Date(2012, 6, 1, 9, 0))); } - @Test(expected = IllegalArgumentException.class) + @Test public void with0Increment() { - new CronSequenceGenerator("*/0 * * * * *").next(new Date(2012, 6, 1, 9, 0)); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronSequenceGenerator("*/0 * * * * *").next(new Date(2012, 6, 1, 9, 0))); } - @Test(expected = IllegalArgumentException.class) + @Test public void withNegativeIncrement() { - new CronSequenceGenerator("*/-1 * * * * *").next(new Date(2012, 6, 1, 9, 0)); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronSequenceGenerator("*/-1 * * * * *").next(new Date(2012, 6, 1, 9, 0))); } - @Test(expected = IllegalArgumentException.class) + @Test public void withInvertedMinuteRange() { - new CronSequenceGenerator("* 6-5 * * * *").next(new Date(2012, 6, 1, 9, 0)); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronSequenceGenerator("* 6-5 * * * *").next(new Date(2012, 6, 1, 9, 0))); } - @Test(expected = IllegalArgumentException.class) + @Test public void withInvertedHourRange() { - new CronSequenceGenerator("* * 6-5 * * *").next(new Date(2012, 6, 1, 9, 0)); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronSequenceGenerator("* * 6-5 * * *").next(new Date(2012, 6, 1, 9, 0))); } @Test diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java index 79eec30f0f8..26f1b334dc5 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java @@ -31,6 +31,7 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.scheduling.TriggerContext; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -488,7 +489,7 @@ public class CronTriggerTests { assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNonExistentSpecificDate() throws Exception { // TODO: maybe try and detect this as a special case in parser? CronTrigger trigger = new CronTrigger("0 0 0 31 6 *", timeZone); @@ -496,7 +497,8 @@ public class CronTriggerTests { calendar.set(Calendar.MONTH, 2); Date date = calendar.getTime(); TriggerContext context1 = getTriggerContext(date); - trigger.nextExecutionTime(context1); + assertThatIllegalArgumentException().isThrownBy(() -> + trigger.nextExecutionTime(context1)); // new CronTrigger("0 0 0 30 1 ?", timeZone); } @@ -605,64 +607,76 @@ public class CronTriggerTests { assertEquals(trigger1, trigger2); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSecondInvalid() throws Exception { - new CronTrigger("77 * * * * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("77 * * * * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSecondRangeInvalid() throws Exception { - new CronTrigger("44-77 * * * * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("44-77 * * * * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMinuteInvalid() throws Exception { - new CronTrigger("* 77 * * * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* 77 * * * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMinuteRangeInvalid() throws Exception { - new CronTrigger("* 44-77 * * * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* 44-77 * * * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testHourInvalid() throws Exception { - new CronTrigger("* * 27 * * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* * 27 * * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testHourRangeInvalid() throws Exception { - new CronTrigger("* * 23-28 * * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* * 23-28 * * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDayInvalid() throws Exception { - new CronTrigger("* * * 45 * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* * * 45 * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDayRangeInvalid() throws Exception { - new CronTrigger("* * * 28-45 * *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* * * 28-45 * *", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMonthInvalid() throws Exception { - new CronTrigger("0 0 0 25 13 ?", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("0 0 0 25 13 ?", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMonthInvalidTooSmall() throws Exception { - new CronTrigger("0 0 0 25 0 ?", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("0 0 0 25 0 ?", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDayOfMonthInvalid() throws Exception { - new CronTrigger("0 0 0 32 12 ?", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("0 0 0 32 12 ?", timeZone)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMonthRangeInvalid() throws Exception { - new CronTrigger("* * * * 11-13 *", timeZone); + assertThatIllegalArgumentException().isThrownBy(() -> + new CronTrigger("* * * * 11-13 *", timeZone)); } @Test diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java index 345394bfa3b..8e655c42f55 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java @@ -37,6 +37,8 @@ import org.springframework.scripting.TestBeanAwareMessenger; import org.springframework.scripting.support.ScriptFactoryPostProcessor; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -44,7 +46,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -199,13 +200,9 @@ public class BshScriptFactoryTests { @Test public void scriptCompilationException() { - try { - new ClassPathXmlApplicationContext("org/springframework/scripting/bsh/bshBrokenContext.xml"); - fail("Must throw exception for broken script file"); - } - catch (NestedRuntimeException ex) { - assertTrue(ex.contains(ScriptCompilationException.class)); - } + assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext("org/springframework/scripting/bsh/bshBrokenContext.xml")) + .matches(ex -> ex.contains(ScriptCompilationException.class)); } @Test @@ -216,43 +213,28 @@ public class BshScriptFactoryTests { given(script.isModified()).willReturn(true); BshScriptFactory factory = new BshScriptFactory( ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX + badScript, Messenger.class); - try { + assertThatExceptionOfType(BshScriptUtils.BshExecutionException.class).isThrownBy(() -> { Messenger messenger = (Messenger) factory.getScriptedObject(script, Messenger.class); messenger.getMessage(); - fail("Must have thrown a BshScriptUtils.BshExecutionException."); - } - catch (BshScriptUtils.BshExecutionException expected) { - } + }); } @Test public void ctorWithNullScriptSourceLocator() { - try { - new BshScriptFactory(null, Messenger.class); - fail("Must have thrown exception by this point."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new BshScriptFactory(null, Messenger.class)); } @Test public void ctorWithEmptyScriptSourceLocator() { - try { - new BshScriptFactory("", Messenger.class); - fail("Must have thrown exception by this point."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new BshScriptFactory("", Messenger.class)); } @Test public void ctorWithWhitespacedScriptSourceLocator() { - try { - new BshScriptFactory("\n ", Messenger.class); - fail("Must have thrown exception by this point."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new BshScriptFactory("\n ", Messenger.class)); } @Test diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java index c5c2d9ee877..4f13f20a1bf 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java @@ -21,8 +21,8 @@ import org.junit.Test; import org.springframework.context.support.GenericXmlApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Dave Syer @@ -38,15 +38,10 @@ public class GroovyAspectIntegrationTests { LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); - try { - bean.sayHello(); - fail("Expected exception"); - } - catch (RuntimeException ex) { - assertEquals("TestServiceImpl", ex.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + bean::sayHello) + .withMessage("TestServiceImpl"); assertEquals(1, logAdvice.getCountThrows()); - } @Test @@ -56,13 +51,9 @@ public class GroovyAspectIntegrationTests { LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); - try { - bean.sayHello(); - fail("Expected exception"); - } - catch (RuntimeException ex) { - assertEquals("GroovyServiceImpl", ex.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + bean::sayHello) + .withMessage("GroovyServiceImpl"); assertEquals(1, logAdvice.getCountThrows()); } @@ -74,13 +65,9 @@ public class GroovyAspectIntegrationTests { LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); - try { - bean.sayHello(); - fail("Expected exception"); - } - catch (RuntimeException ex) { - assertEquals("GroovyServiceImpl", ex.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + bean::sayHello) + .withMessage("GroovyServiceImpl"); // No proxy here because the pointcut only applies to the concrete class, not the interface assertEquals(0, logAdvice.getCountThrows()); assertEquals(0, logAdvice.getCountBefore()); @@ -93,13 +80,9 @@ public class GroovyAspectIntegrationTests { LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); - try { - bean.sayHello(); - fail("Expected exception"); - } - catch (TestException ex) { - assertEquals("GroovyServiceImpl", ex.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + bean::sayHello) + .withMessage("GroovyServiceImpl"); assertEquals(1, logAdvice.getCountBefore()); assertEquals(1, logAdvice.getCountThrows()); } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java index cca6ab8d236..7e5a772ba1c 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java @@ -26,8 +26,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.scripting.support.ResourceScriptSource; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Dave Syer @@ -95,13 +95,9 @@ public class GroovyAspectTests { TestService bean = (TestService) factory.getProxy(); assertEquals(0, logAdvice.getCountThrows()); - try { - bean.sayHello(); - fail("Expected exception"); - } - catch (TestException ex) { - assertEquals(message, ex.getMessage()); - } + assertThatExceptionOfType(TestException.class).isThrownBy( + bean::sayHello) + .withMessage(message); assertEquals(1, logAdvice.getCountThrows()); } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index 315f9137aab..c3fd6af88b6 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -45,13 +45,16 @@ import org.springframework.stereotype.Component; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -262,13 +265,9 @@ public class GroovyScriptFactoryTests { @Test public void testScriptCompilationException() throws Exception { - try { - new ClassPathXmlApplicationContext("org/springframework/scripting/groovy/groovyBrokenContext.xml"); - fail("Should throw exception for broken script file"); - } - catch (NestedRuntimeException ex) { - assertTrue("Wrong root cause: " + ex, ex.contains(ScriptCompilationException.class)); - } + assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext("org/springframework/scripting/groovy/groovyBrokenContext.xml")) + .matches(ex -> ex.contains(ScriptCompilationException.class)); } @Test @@ -279,13 +278,9 @@ public class GroovyScriptFactoryTests { given(script.suggestedClassName()).willReturn("someName"); GroovyScriptFactory factory = new GroovyScriptFactory(ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX + badScript); - try { - factory.getScriptedObject(script); - fail("Must have thrown a ScriptCompilationException (no public no-arg ctor in scripted class)."); - } - catch (ScriptCompilationException expected) { - assertTrue(expected.contains(NoSuchMethodException.class)); - } + assertThatExceptionOfType(ScriptCompilationException.class).isThrownBy(() -> + factory.getScriptedObject(script)) + .matches(ex -> ex.contains(NoSuchMethodException.class)); } @Test @@ -312,55 +307,35 @@ public class GroovyScriptFactoryTests { @Test public void testWithTwoClassesDefinedInTheOneGroovyFile_WrongClassFirst() throws Exception { - try { - ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass()); - ctx.getBean("messenger", Messenger.class); - fail("Must have failed: two classes defined in GroovyScriptFactory source, non-Messenger class defined first."); - } - // just testing for failure here, hence catching Exception... - catch (Exception expected) { - } + assertThatExceptionOfType(Exception.class).as("two classes defined in GroovyScriptFactory source, non-Messenger class defined first").isThrownBy(() -> { + ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass()); + ctx.getBean("messenger", Messenger.class); + }); } @Test public void testCtorWithNullScriptSourceLocator() throws Exception { - try { - new GroovyScriptFactory(null); - fail("Must have thrown exception by this point."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new GroovyScriptFactory(null)); } @Test public void testCtorWithEmptyScriptSourceLocator() throws Exception { - try { - new GroovyScriptFactory(""); - fail("Must have thrown exception by this point."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new GroovyScriptFactory("")); } @Test public void testCtorWithWhitespacedScriptSourceLocator() throws Exception { - try { - new GroovyScriptFactory("\n "); - fail("Must have thrown exception by this point."); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + new GroovyScriptFactory("\n ")); } @Test public void testWithInlineScriptWithLeadingWhitespace() throws Exception { - try { - new ClassPathXmlApplicationContext("lwspBadGroovyContext.xml", getClass()); - fail("Must have thrown a BeanCreationException ('inline:' prefix was preceded by whitespace"); - } - catch (BeanCreationException expected) { - assertTrue(expected.contains(FileNotFoundException.class)); - } + assertThatExceptionOfType(BeanCreationException.class).as("'inline:' prefix was preceded by whitespace").isThrownBy(() -> + new ClassPathXmlApplicationContext("lwspBadGroovyContext.xml", getClass())) + .matches(ex -> ex.contains(FileNotFoundException.class)); } @Test @@ -377,12 +352,8 @@ public class GroovyScriptFactoryTests { @Test public void testGetScriptedObjectDoesChokeOnNullScriptSourceBeingPassedIn() throws Exception { GroovyScriptFactory factory = new GroovyScriptFactory("a script source locator (doesn't matter here)"); - try { - factory.getScriptedObject(null); - fail("Must have thrown a NullPointerException as per contract ('null' ScriptSource supplied"); - } - catch (NullPointerException expected) { - } + assertThatNullPointerException().as("NullPointerException as per contract ('null' ScriptSource supplied)").isThrownBy(() -> + factory.getScriptedObject(null)); } @Test @@ -556,15 +527,11 @@ public class GroovyScriptFactoryTests { private void testMetaClass(String xmlFile) { // expect the exception we threw in the custom metaclass to show it got invoked - try { - ApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile); - Calculator calc = (Calculator) ctx.getBean("delegatingCalculator"); - calc.add(1, 2); - fail("expected IllegalStateException"); - } - catch (IllegalStateException ex) { - assertEquals("Gotcha", ex.getMessage()); - } + ApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile); + Calculator calc = (Calculator) ctx.getBean("delegatingCalculator"); + assertThatIllegalStateException().isThrownBy(() -> + calc.add(1, 2)) + .withMessage("Gotcha"); } @Test diff --git a/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java index 22a52d1cf51..1f7202ae65b 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java @@ -20,6 +20,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -27,9 +28,10 @@ import static org.mockito.Mockito.mock; */ public class RefreshableScriptTargetSourceTests { - @Test(expected = IllegalArgumentException.class) + @Test public void createWithNullScriptSource() throws Exception { - new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false); + assertThatIllegalArgumentException().isThrownBy(() -> + new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false)); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java index 24207a11e36..f359005706c 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java @@ -31,11 +31,11 @@ import org.springframework.scripting.groovy.GroovyScriptFactory; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -91,12 +91,8 @@ public class ScriptFactoryPostProcessorTests { @Test public void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() throws Exception { - try { - new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class)); - fail("Must have thrown exception by this point."); - } - catch (IllegalStateException expected) { - } + assertThatIllegalStateException().isThrownBy(() -> + new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class))); } @Test @@ -213,13 +209,9 @@ public class ScriptFactoryPostProcessorTests { // needs The Sundays compiler; must NOT throw any exception here... source.setScript("I keep hoping you are the same as me, and I'll send you letters and come to your house for tea"); Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - try { - refreshedMessenger.getMessage(); - fail("Must have thrown an Exception (invalid script)"); - } - catch (FatalBeanException expected) { - assertTrue(expected.contains(ScriptCompilationException.class)); - } + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + refreshedMessenger.getMessage()) + .matches(ex -> ex.contains(ScriptCompilationException.class)); } @Test diff --git a/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java index 2d1ea85d653..00a65b6ef97 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java @@ -18,6 +18,7 @@ package org.springframework.scripting.support; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -35,19 +36,22 @@ public class StaticScriptSourceTests { private final StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); - @Test(expected = IllegalArgumentException.class) + @Test public void createWithNullScript() throws Exception { - new StaticScriptSource(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new StaticScriptSource(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void createWithEmptyScript() throws Exception { - new StaticScriptSource(""); + assertThatIllegalArgumentException().isThrownBy(() -> + new StaticScriptSource("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void createWithWhitespaceOnlyScript() throws Exception { - new StaticScriptSource(" \n\n\t \t\n"); + assertThatIllegalArgumentException().isThrownBy(() -> + new StaticScriptSource(" \n\n\t \t\n")); } @Test diff --git a/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java b/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java index 4d0aecfe90c..4010da14105 100644 --- a/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java +++ b/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java @@ -34,6 +34,7 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -100,10 +101,11 @@ public class ModelMapTests { assertEquals("bing", string); } - @Test(expected = IllegalArgumentException.class) + @Test public void testOneArgCtorWithNull() { //Null model arguments added without a name being explicitly supplied are not allowed - new ModelMap(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ModelMap(null)); } @Test @@ -124,11 +126,12 @@ public class ModelMapTests { assertEquals(0, model.size()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddObjectWithNull() throws Exception { // Null model arguments added without a name being explicitly supplied are not allowed ModelMap model = new ModelMap(); - model.addAttribute(null); + assertThatIllegalArgumentException().isThrownBy(() -> + model.addAttribute(null)); } @Test @@ -154,14 +157,15 @@ public class ModelMapTests { assertEquals(0, model.size()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddAllObjectsWithSparseArrayList() throws Exception { // Null model arguments added without a name being explicitly supplied are not allowed ModelMap model = new ModelMap(); ArrayList list = new ArrayList<>(); list.add("bing"); list.add(null); - model.addAllAttributes(list); + assertThatIllegalArgumentException().isThrownBy(() -> + model.addAllAttributes(list)); } @Test diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java index 36d86a29fa9..55aec0b3aa0 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java @@ -28,11 +28,10 @@ import org.springframework.beans.PropertyValue; import org.springframework.tests.sample.beans.FieldAccessBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -74,14 +73,8 @@ public class DataBinderFieldAccessTests { pvs.addPropertyValue(new PropertyValue("name", "Rod")); pvs.addPropertyValue(new PropertyValue("age", new Integer(32))); pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue")); - - try { - binder.bind(pvs); - fail("Should have thrown NotWritablePropertyException"); - } - catch (NotWritablePropertyException ex) { - // expected - } + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + binder.bind(pvs)); } @Test @@ -93,31 +86,24 @@ public class DataBinderFieldAccessTests { pvs.addPropertyValue(new PropertyValue("name", "Rod")); pvs.addPropertyValue(new PropertyValue("age", "32x")); binder.bind(pvs); + assertThatExceptionOfType(BindException.class).isThrownBy( + binder::close) + .satisfies(ex -> { + assertThat(rod.getName()).isEqualTo("Rod"); + Map map = binder.getBindingResult().getModel(); + FieldAccessBean tb = (FieldAccessBean) map.get("person"); + assertThat(tb).isEqualTo(rod); - try { - binder.close(); - fail("Should have thrown BindException"); - } - catch (BindException ex) { - assertTrue("changed name correctly", rod.getName().equals("Rod")); - //assertTrue("changed age correctly", rod.getAge() == 32); - - Map map = binder.getBindingResult().getModel(); - //assertTrue("There are 3 element in map", m.size() == 1); - FieldAccessBean tb = (FieldAccessBean) map.get("person"); - assertTrue("Same object", tb.equals(rod)); - - BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person"); - assertTrue("Added itself to map", br == binder.getBindingResult()); - assertTrue(br.hasErrors()); - assertTrue("Correct number of errors", br.getErrorCount() == 1); - - assertTrue("Has age errors", br.hasFieldErrors("age")); - assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1); - assertEquals("32x", binder.getBindingResult().getFieldValue("age")); - assertEquals("32x", binder.getBindingResult().getFieldError("age").getRejectedValue()); - assertEquals(0, tb.getAge()); - } + BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person"); + assertThat(br).isSameAs(binder.getBindingResult()); + assertThat(br.hasErrors()).isTrue(); + assertThat(br.getErrorCount()).isEqualTo(1); + assertThat(br.hasFieldErrors()).isTrue(); + assertThat(br.getFieldErrorCount("age")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x"); + assertThat(binder.getBindingResult().getFieldError("age").getRejectedValue()).isEqualTo("32x"); + assertThat(tb.getAge()).isEqualTo(0); + }); } @Test @@ -171,34 +157,25 @@ public class DataBinderFieldAccessTests { pvs.addPropertyValue(new PropertyValue("spouse", "Kerry")); binder.bind(pvs); - try { - binder.close(); - fail("Should have thrown BindException"); - } - catch (BindException ex) { - assertTrue("changed name correctly", rod.getName().equals("Rod")); - //assertTrue("changed age correctly", rod.getAge() == 32); - - Map model = binder.getBindingResult().getModel(); - //assertTrue("There are 3 element in map", m.size() == 1); - FieldAccessBean tb = (FieldAccessBean) model.get("person"); - assertTrue("Same object", tb.equals(rod)); - - BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person"); - assertTrue("Added itself to map", br == binder.getBindingResult()); - assertTrue(br.hasErrors()); - assertTrue("Correct number of errors", br.getErrorCount() == 1); - - assertTrue("Has age errors", br.hasFieldErrors("age")); - assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1); - assertEquals("32x", binder.getBindingResult().getFieldValue("age")); - assertEquals("32x", binder.getBindingResult().getFieldError("age").getRejectedValue()); - assertEquals(0, tb.getAge()); - - assertTrue("Does not have spouse errors", !br.hasFieldErrors("spouse")); - assertEquals("Kerry", binder.getBindingResult().getFieldValue("spouse")); - assertNotNull(tb.getSpouse()); - } + assertThatExceptionOfType(BindException.class).isThrownBy( + binder::close) + .satisfies(ex -> { + assertThat(rod.getName()).isEqualTo("Rod"); + Map model = binder.getBindingResult().getModel(); + FieldAccessBean tb = (FieldAccessBean) model.get("person"); + assertThat(tb).isEqualTo(rod); + BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person"); + assertThat(br).isSameAs(binder.getBindingResult()); + assertThat(br.hasErrors()).isTrue(); + assertThat(br.getErrorCount()).isEqualTo(1); + assertThat(br.hasFieldErrors("age")).isTrue(); + assertThat(br.getFieldErrorCount("age")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x"); + assertThat(binder.getBindingResult().getFieldError("age").getRejectedValue()).isEqualTo("32x"); + assertThat(tb.getAge()).isEqualTo(0); + assertThat(br.hasFieldErrors("spouse")).isFalse(); + assertThat(binder.getBindingResult().getFieldValue("spouse")).isEqualTo("Kerry"); + assertThat(tb.getSpouse()).isNotNull(); + }); } - } diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java index cb3afc9619d..5e8af88d687 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java @@ -67,14 +67,14 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -159,14 +159,8 @@ public class DataBinderTests { pvs.add("name", "Rod"); pvs.add("age", 32); pvs.add("nonExisting", "someValue"); - - try { - binder.bind(pvs); - fail("Should have thrown NotWritablePropertyException"); - } - catch (NotWritablePropertyException ex) { - // expected - } + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + binder.bind(pvs)); } @Test @@ -176,14 +170,8 @@ public class DataBinderTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "Rod"); pvs.add("spouse.age", 32); - - try { - binder.bind(pvs); - fail("Should have thrown NullValueInNestedPathException"); - } - catch (NullValueInNestedPathException ex) { - // expected - } + assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() -> + binder.bind(pvs)); } @Test @@ -207,68 +195,57 @@ public class DataBinderTests { pvs.add("age", "32x"); pvs.add("touchy", "m.y"); binder.bind(pvs); + assertThatExceptionOfType(BindException.class).isThrownBy( + binder::close) + .satisfies(ex -> { + assertThat(rod.getName()).isEqualTo("Rod"); + Map map = binder.getBindingResult().getModel(); + TestBean tb = (TestBean) map.get("person"); + assertThat(tb).isSameAs(rod); - try { - binder.close(); - fail("Should have thrown BindException"); - } - catch (BindException ex) { - assertTrue("changed name correctly", rod.getName().equals("Rod")); - //assertTrue("changed age correctly", rod.getAge() == 32); + BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person"); + assertThat(BindingResultUtils.getBindingResult(map, "person")).isEqualTo(br); + assertThat(BindingResultUtils.getRequiredBindingResult(map, "person")).isEqualTo(br); - Map map = binder.getBindingResult().getModel(); - //assertTrue("There are 3 element in map", m.size() == 1); - TestBean tb = (TestBean) map.get("person"); - assertTrue("Same object", tb.equals(rod)); + assertThat(BindingResultUtils.getBindingResult(map, "someOtherName")).isNull(); + assertThatIllegalStateException().isThrownBy(() -> + BindingResultUtils.getRequiredBindingResult(map, "someOtherName")); - BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person"); - assertSame(br, BindingResultUtils.getBindingResult(map, "person")); - assertSame(br, BindingResultUtils.getRequiredBindingResult(map, "person")); + assertThat(binder.getBindingResult()).as("Added itself to map").isSameAs(br); + assertThat(br.hasErrors()).isTrue(); + assertThat(br.getErrorCount()).isEqualTo(2); - assertNull(BindingResultUtils.getBindingResult(map, "someOtherName")); - try { - BindingResultUtils.getRequiredBindingResult(map, "someOtherName"); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException expected) { - } + assertThat(br.hasFieldErrors("age")).isTrue(); + assertThat(br.getFieldErrorCount("age")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x"); + FieldError ageError = binder.getBindingResult().getFieldError("age"); + assertThat(ageError).isNotNull(); + assertThat(ageError.getCode()).isEqualTo("typeMismatch"); + assertThat(ageError.getRejectedValue()).isEqualTo("32x"); + assertThat(ageError.contains(TypeMismatchException.class)).isTrue(); + assertThat(ageError.contains(NumberFormatException.class)).isTrue(); + assertThat(ageError.unwrap(NumberFormatException.class).getMessage()).contains("32x"); + assertThat(tb.getAge()).isEqualTo(0); - assertTrue("Added itself to map", br == binder.getBindingResult()); - assertTrue(br.hasErrors()); - assertTrue("Correct number of errors", br.getErrorCount() == 2); + assertThat(br.hasFieldErrors("touchy")).isTrue(); + assertThat(br.getFieldErrorCount("touchy")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("m.y"); + FieldError touchyError = binder.getBindingResult().getFieldError("touchy"); + assertThat(touchyError).isNotNull(); + assertThat(touchyError.getCode()).isEqualTo("methodInvocation"); + assertThat(touchyError.getRejectedValue()).isEqualTo("m.y"); + assertThat(touchyError.contains(MethodInvocationException.class)).isTrue(); + assertThat(touchyError.unwrap(MethodInvocationException.class).getCause().getMessage()).contains("a ."); + assertThat(tb.getTouchy()).isNull(); - assertTrue("Has age errors", br.hasFieldErrors("age")); - assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1); - assertEquals("32x", binder.getBindingResult().getFieldValue("age")); - FieldError ageError = binder.getBindingResult().getFieldError("age"); - assertNotNull(ageError); - assertEquals("typeMismatch", ageError.getCode()); - assertEquals("32x", ageError.getRejectedValue()); - assertTrue(ageError.contains(TypeMismatchException.class)); - assertTrue(ageError.contains(NumberFormatException.class)); - assertTrue(ageError.unwrap(NumberFormatException.class).getMessage().contains("32x")); - assertEquals(0, tb.getAge()); - - assertTrue("Has touchy errors", br.hasFieldErrors("touchy")); - assertTrue("Correct number of touchy errors", br.getFieldErrorCount("touchy") == 1); - assertEquals("m.y", binder.getBindingResult().getFieldValue("touchy")); - FieldError touchyError = binder.getBindingResult().getFieldError("touchy"); - assertNotNull(touchyError); - assertEquals("methodInvocation", touchyError.getCode()); - assertEquals("m.y", touchyError.getRejectedValue()); - assertTrue(touchyError.contains(MethodInvocationException.class)); - assertTrue(touchyError.unwrap(MethodInvocationException.class).getCause().getMessage().contains("a .")); - assertNull(tb.getTouchy()); - - rod = new TestBean(); - binder = new DataBinder(rod, "person"); - pvs = new MutablePropertyValues(); - pvs.add("name", "Rod"); - pvs.add("age", "32x"); - pvs.add("touchy", "m.y"); - binder.bind(pvs); - assertEquals(binder.getBindingResult(), ex.getBindingResult()); - } + DataBinder binder2 = new DataBinder(new TestBean(), "person"); + MutablePropertyValues pvs2 = new MutablePropertyValues(); + pvs2.add("name", "Rod"); + pvs2.add("age", "32x"); + pvs2.add("touchy", "m.y"); + binder2.bind(pvs2); + assertEquals(binder2.getBindingResult(), ex.getBindingResult()); + }); } @Test @@ -278,14 +255,9 @@ public class DataBinderTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("class.classLoader.URLs[0]", "https://myserver"); binder.setIgnoreUnknownFields(false); - - try { - binder.bind(pvs); - fail("Should have thrown NotWritablePropertyException"); - } - catch (NotWritablePropertyException ex) { - assertTrue(ex.getMessage().contains("classLoader")); - } + assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> + binder.bind(pvs)) + .withMessageContaining("classLoader"); } @Test @@ -319,46 +291,41 @@ public class DataBinderTests { pvs.add("spouse", "Kerry"); binder.bind(pvs); - try { - binder.close(); - fail("Should have thrown BindException"); - } - catch (BindException ex) { - assertTrue("changed name correctly", rod.getName().equals("Rod")); - //assertTrue("changed age correctly", rod.getAge() == 32); + assertThatExceptionOfType(BindException.class).isThrownBy( + binder::close) + .satisfies(ex -> { + assertThat(rod.getName()).isEqualTo("Rod"); + Map model = binder.getBindingResult().getModel(); + TestBean tb = (TestBean) model.get("person"); + assertThat(tb).isEqualTo(rod); - Map model = binder.getBindingResult().getModel(); - //assertTrue("There are 3 element in map", m.size() == 1); - TestBean tb = (TestBean) model.get("person"); - assertTrue("Same object", tb.equals(rod)); + BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person"); + assertThat(binder.getBindingResult()).isSameAs(br); + assertThat(br.hasErrors()).isTrue(); + assertThat(br.getErrorCount()).isEqualTo(2); - BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person"); - assertTrue("Added itself to map", br == binder.getBindingResult()); - assertTrue(br.hasErrors()); - assertTrue("Correct number of errors", br.getErrorCount() == 2); + assertThat(br.hasFieldErrors("age")).isTrue(); + assertThat(br.getFieldErrorCount("age")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x"); + FieldError ageError = binder.getBindingResult().getFieldError("age"); + assertThat(ageError).isNotNull(); + assertThat(ageError.getCode()).isEqualTo("typeMismatch"); + assertThat(ageError.getRejectedValue()).isEqualTo("32x"); + assertThat(tb.getAge()).isEqualTo(0); - assertTrue("Has age errors", br.hasFieldErrors("age")); - assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1); - assertEquals("32x", binder.getBindingResult().getFieldValue("age")); - FieldError ageError = binder.getBindingResult().getFieldError("age"); - assertNotNull(ageError); - assertEquals("typeMismatch", ageError.getCode()); - assertEquals("32x", ageError.getRejectedValue()); - assertEquals(0, tb.getAge()); + assertThat(br.hasFieldErrors("touchy")).isTrue(); + assertThat(br.getFieldErrorCount("touchy")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("m.y"); + FieldError touchyError = binder.getBindingResult().getFieldError("touchy"); + assertThat(touchyError).isNotNull(); + assertThat(touchyError.getCode()).isEqualTo("methodInvocation"); + assertThat(touchyError.getRejectedValue()).isEqualTo("m.y"); + assertThat(tb.getTouchy()).isNull(); - assertTrue("Has touchy errors", br.hasFieldErrors("touchy")); - assertTrue("Correct number of touchy errors", br.getFieldErrorCount("touchy") == 1); - assertEquals("m.y", binder.getBindingResult().getFieldValue("touchy")); - FieldError touchyError = binder.getBindingResult().getFieldError("touchy"); - assertNotNull(touchyError); - assertEquals("methodInvocation", touchyError.getCode()); - assertEquals("m.y", touchyError.getRejectedValue()); - assertNull(tb.getTouchy()); - - assertTrue("Does not have spouse errors", !br.hasFieldErrors("spouse")); - assertEquals("Kerry", binder.getBindingResult().getFieldValue("spouse")); - assertNotNull(tb.getSpouse()); - } + assertThat(br.hasFieldErrors("spouse")).isFalse(); + assertThat(binder.getBindingResult().getFieldValue("spouse")).isEqualTo("Kerry"); + assertThat(tb.getSpouse()).isNotNull(); + }); } @Test @@ -1159,16 +1126,11 @@ public class DataBinderTests { } @Test - public void testValidatorNoErrors() { + public void testValidatorNoErrors() throws Exception { TestBean tb = new TestBean(); tb.setAge(33); tb.setName("Rod"); - try { - tb.setTouchy("Rod"); - } - catch (Exception e) { - fail("Should not throw any Exception"); - } + tb.setTouchy("Rod"); // Should not throw TestBean tb2 = new TestBean(); tb2.setAge(34); tb.setSpouse(tb2); @@ -1929,14 +1891,9 @@ public class DataBinderTests { MutablePropertyValues mpvs = new MutablePropertyValues(); mpvs.add("friends[256]", ""); - try { - binder.bind(mpvs); - fail("Should have thrown InvalidPropertyException"); - } - catch (InvalidPropertyException ex) { - // expected - assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); - } + assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() -> + binder.bind(mpvs)) + .satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(IndexOutOfBoundsException.class)); } @Test @@ -1960,14 +1917,9 @@ public class DataBinderTests { MutablePropertyValues mpvs = new MutablePropertyValues(); mpvs.add("friends[16]", ""); - try { - binder.bind(mpvs); - fail("Should have thrown InvalidPropertyException"); - } - catch (InvalidPropertyException ex) { - // expected - assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); - } + assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() -> + binder.bind(mpvs)) + .satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(IndexOutOfBoundsException.class)); } @Test diff --git a/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java b/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java index e702fc4f093..77703ef58ea 100644 --- a/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -35,17 +36,19 @@ import static org.junit.Assert.assertTrue; */ public class ValidationUtilsTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testInvokeValidatorWithNullValidator() throws Exception { TestBean tb = new TestBean(); Errors errors = new BeanPropertyBindingResult(tb, "tb"); - ValidationUtils.invokeValidator(null, tb, errors); + assertThatIllegalArgumentException().isThrownBy(() -> + ValidationUtils.invokeValidator(null, tb, errors)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInvokeValidatorWithNullErrors() throws Exception { TestBean tb = new TestBean(); - ValidationUtils.invokeValidator(new EmptyValidator(), tb, null); + assertThatIllegalArgumentException().isThrownBy(() -> + ValidationUtils.invokeValidator(new EmptyValidator(), tb, null)); } @Test diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java index 401e4eb887f..0c7eb5632c5 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java @@ -31,9 +31,9 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncAnnotationAdvisor; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -46,14 +46,9 @@ public class BeanValidationPostProcessorTests { ac.registerBeanDefinition("bvpp", new RootBeanDefinition(BeanValidationPostProcessor.class)); ac.registerBeanDefinition("capp", new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class)); ac.registerBeanDefinition("bean", new RootBeanDefinition(NotNullConstrainedBean.class)); - try { - ac.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getRootCause().getMessage().contains("testBean")); - assertTrue(ex.getRootCause().getMessage().contains("invalid")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + ac::refresh) + .satisfies(ex -> assertThat(ex.getRootCause().getMessage()).contains("testBean").contains("invalid")); ac.close(); } @@ -103,14 +98,9 @@ public class BeanValidationPostProcessorTests { bd.getPropertyValues().add("testBean", new TestBean()); bd.getPropertyValues().add("stringValue", "s"); ac.registerBeanDefinition("bean", bd); - try { - ac.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.getRootCause().getMessage().contains("stringValue")); - assertTrue(ex.getRootCause().getMessage().contains("invalid")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + ac.refresh()) + .satisfies(ex -> assertThat(ex.getRootCause().getMessage()).contains("stringValue").contains("invalid")); ac.close(); } diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java index 03629684662..cea70093b79 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java @@ -18,6 +18,7 @@ package org.springframework.validation.beanvalidation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import javax.validation.ValidationException; import javax.validation.Validator; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; @@ -38,9 +39,9 @@ import org.springframework.scheduling.annotation.AsyncAnnotationAdvisor; import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor; import org.springframework.validation.annotation.Validated; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -71,52 +72,20 @@ public class MethodValidationTests { private void doTestProxyValidation(MyValidInterface proxy) { assertNotNull(proxy.myValidMethod("value", 5)); - try { - assertNotNull(proxy.myValidMethod("value", 15)); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - try { - assertNotNull(proxy.myValidMethod(null, 5)); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - try { - assertNotNull(proxy.myValidMethod("value", 0)); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidMethod("value", 15)); + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidMethod(null, 5)); + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidMethod("value", 0)); proxy.myValidAsyncMethod("value", 5); - try { - proxy.myValidAsyncMethod("value", 15); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - try { - proxy.myValidAsyncMethod(null, 5); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } - + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidAsyncMethod("value", 15)); + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myValidAsyncMethod(null, 5)); assertEquals("myValue", proxy.myGenericMethod("myValue")); - try { - proxy.myGenericMethod(null); - fail("Should have thrown ValidationException"); - } - catch (javax.validation.ValidationException ex) { - // expected - } + assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> + proxy.myGenericMethod(null)); } @Test 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 4252ce668df..b458fbc4481 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 @@ -51,13 +51,13 @@ import org.springframework.validation.Errors; 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; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -74,12 +74,8 @@ public class ValidatorFactoryTests { assertEquals(2, result.size()); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); - if ("name".equals(path) || "address.street".equals(path)) { - assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull); - } - else { - fail("Invalid constraint violation with path '" + path + "'"); - } + assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); + assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class); } Validator nativeValidator = validator.unwrap(Validator.class); @@ -101,12 +97,8 @@ public class ValidatorFactoryTests { assertEquals(2, result.size()); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); - if ("name".equals(path) || "address.street".equals(path)) { - assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull); - } - else { - fail("Invalid constraint violation with path '" + path + "'"); - } + assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); + assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class); } Validator nativeValidator = validator.unwrap(Validator.class); 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 bf0fecbcefd..23691826cca 100644 --- a/spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java +++ b/spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java @@ -39,11 +39,12 @@ import org.junit.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +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.junit.Assert.fail; import static org.springframework.core.CollectionFactory.createApproximateCollection; import static org.springframework.core.CollectionFactory.createApproximateMap; import static org.springframework.core.CollectionFactory.createCollection; @@ -75,16 +76,13 @@ public class CollectionFactoryTests { // Use a try-catch block to ensure that the exception is thrown as a result of the // next line and not as a result of the previous line. - try { - // Note that ints is of type Collection, but the collection returned - // by createApproximateCollection() is of type Collection. Thus, 42 - // cannot be cast to a Color. - ints.add(42); - fail("Should have thrown a ClassCastException"); - } - catch (ClassCastException e) { - /* expected */ - } + + // Note that ints is of type Collection, but the collection returned + // by createApproximateCollection() is of type Collection. Thus, 42 + // cannot be cast to a Color. + + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + ints.add(42)); } @Test @@ -93,16 +91,13 @@ public class CollectionFactoryTests { // Use a try-catch block to ensure that the exception is thrown as a result of the // next line and not as a result of the previous line. - try { - // Note that ints is of type Collection, but the collection returned - // by createCollection() is of type Collection. Thus, 42 cannot be cast - // to a Color. - ints.add(42); - fail("Should have thrown a ClassCastException"); - } - catch (ClassCastException e) { - /* expected */ - } + + // Note that ints is of type Collection, but the collection returned + // by createCollection() is of type Collection. Thus, 42 cannot be cast + // to a Color. + + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + ints.add(42)); } /** @@ -121,16 +116,13 @@ public class CollectionFactoryTests { // Use a try-catch block to ensure that the exception is thrown as a result of the // next line and not as a result of the previous line. - try { - // Note that the 'map' key must be of type String, but the keys in the map - // returned by createApproximateMap() are of type Color. Thus "foo" cannot be - // cast to a Color. - map.put("foo", 1); - fail("Should have thrown a ClassCastException"); - } - catch (ClassCastException e) { - /* expected */ - } + + // Note that the 'map' key must be of type String, but the keys in the map + // returned by createApproximateMap() are of type Color. Thus "foo" cannot be + // cast to a Color. + + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + map.put("foo", 1)); } @Test @@ -139,16 +131,13 @@ public class CollectionFactoryTests { // Use a try-catch block to ensure that the exception is thrown as a result of the // next line and not as a result of the previous line. - try { - // Note that the 'map' key must be of type String, but the keys in the map - // returned by createMap() are of type Color. Thus "foo" cannot be cast to a - // Color. - map.put("foo", 1); - fail("Should have thrown a ClassCastException"); - } - catch (ClassCastException e) { - /* expected */ - } + + // Note that the 'map' key must be of type String, but the keys in the map + // returned by createMap() are of type Color. Thus "foo" cannot be cast to a + // Color. + + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + map.put("foo", 1)); } @Test @@ -157,16 +146,13 @@ public class CollectionFactoryTests { // Use a try-catch block to ensure that the exception is thrown as a result of the // next line and not as a result of the previous line. - try { - // Note: 'map' values must be of type Integer, but the values in the map - // returned by createMap() are of type java.util.List. Thus 1 cannot be - // cast to a List. - map.put("foo", 1); - fail("Should have thrown a ClassCastException"); - } - catch (ClassCastException e) { - /* expected */ - } + + // Note: 'map' values must be of type Integer, but the values in the map + // returned by createMap() are of type java.util.List. Thus 1 cannot be + // cast to a List. + + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + map.put("foo", 1)); } @Test @@ -254,19 +240,22 @@ public class CollectionFactoryTests { assertThat(createCollection(enumSet.getClass(), Color.class, 0), is(instanceOf(enumSet.getClass()))); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsInvalidElementTypeForEnumSet() { - createCollection(EnumSet.class, Object.class, 0); + assertThatIllegalArgumentException().isThrownBy(() -> + createCollection(EnumSet.class, Object.class, 0)); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsNullElementTypeForEnumSet() { - createCollection(EnumSet.class, null, 0); + assertThatIllegalArgumentException().isThrownBy(() -> + createCollection(EnumSet.class, null, 0)); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsNullCollectionType() { - createCollection(null, Object.class, 0); + assertThatIllegalArgumentException().isThrownBy(() -> + createCollection(null, Object.class, 0)); } @Test @@ -293,19 +282,22 @@ public class CollectionFactoryTests { assertThat(createMap(EnumMap.class, Color.class, 0), is(instanceOf(EnumMap.class))); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsInvalidKeyTypeForEnumMap() { - createMap(EnumMap.class, Object.class, 0); + assertThatIllegalArgumentException().isThrownBy(() -> + createMap(EnumMap.class, Object.class, 0)); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsNullKeyTypeForEnumMap() { - createMap(EnumMap.class, null, 0); + assertThatIllegalArgumentException().isThrownBy(() -> + createMap(EnumMap.class, null, 0)); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsNullMapType() { - createMap(null, Object.class, 0); + assertThatIllegalArgumentException().isThrownBy(() -> + createMap(null, Object.class, 0)); } diff --git a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java index 05be973d527..1a33e21da40 100644 --- a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java @@ -21,10 +21,11 @@ import java.util.Set; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -44,20 +45,12 @@ public class ConstantsTests { assertEquals(A.DOG, c.asNumber("dog").intValue()); assertEquals(A.CAT, c.asNumber("cat").intValue()); - try { - c.asNumber("bogus"); - fail("Can't get bogus field"); - } - catch (Constants.ConstantException expected) { - } + assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> + c.asNumber("bogus")); assertTrue(c.asString("S1").equals(A.S1)); - try { - c.asNumber("S1"); - fail("Wrong type"); - } - catch (Constants.ConstantException expected) { - } + assertThatExceptionOfType(Constants.ConstantException.class).as("wrong type").isThrownBy(() -> + c.asNumber("S1")); } @Test @@ -169,27 +162,15 @@ public class ConstantsTests { assertEquals("S1", c.toCode("", "s")); assertEquals("S1", c.toCode("", "s1")); assertEquals("S1", c.toCode("", null)); - try { - c.toCode("bogus", "bogus"); - fail("Should have thrown ConstantException"); - } - catch (Constants.ConstantException expected) { - } - try { - c.toCode("bogus", null); - fail("Should have thrown ConstantException"); - } - catch (Constants.ConstantException expected) { - } + assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> + c.toCode("bogus", "bogus")); + assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> + c.toCode("bogus", null)); assertEquals("MY_PROPERTY_NO", c.toCodeForProperty(Integer.valueOf(1), "myProperty")); assertEquals("MY_PROPERTY_YES", c.toCodeForProperty(Integer.valueOf(2), "myProperty")); - try { - c.toCodeForProperty("bogus", "bogus"); - fail("Should have thrown ConstantException"); - } - catch (Constants.ConstantException expected) { - } + assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> + c.toCodeForProperty("bogus", "bogus")); assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "")); assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "G")); @@ -205,18 +186,10 @@ public class ConstantsTests { assertEquals("S1", c.toCodeForSuffix("", "1")); assertEquals("S1", c.toCodeForSuffix("", "s1")); assertEquals("S1", c.toCodeForSuffix("", null)); - try { - c.toCodeForSuffix("bogus", "bogus"); - fail("Should have thrown ConstantException"); - } - catch (Constants.ConstantException expected) { - } - try { - c.toCodeForSuffix("bogus", null); - fail("Should have thrown ConstantException"); - } - catch (Constants.ConstantException expected) { - } + assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> + c.toCodeForSuffix("bogus", "bogus")); + assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> + c.toCodeForSuffix("bogus", null)); } @Test @@ -251,11 +224,8 @@ public class ConstantsTests { @Test public void ctorWithNullClass() throws Exception { - try { - new Constants(null); - fail("Must have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) {} + assertThatIllegalArgumentException().isThrownBy(() -> + new Constants(null)); } diff --git a/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java b/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java index abe0ffd7e85..11d746a1004 100644 --- a/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java +++ b/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java @@ -27,6 +27,7 @@ import java.util.concurrent.Callable; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -104,9 +105,10 @@ public class MethodParameterTests { assertEquals(longParameter, MethodParameter.forParameter(method.getParameters()[1])); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIndexValidation() { - new MethodParameter(method, 2); + assertThatIllegalArgumentException().isThrownBy(() -> + new MethodParameter(method, 2)); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java b/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java index 848d669f996..149e7ed1385 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -99,9 +100,10 @@ public class SynthesizingMethodParameterTests { assertEquals(longParameter, SynthesizingMethodParameter.forParameter(method.getParameters()[1])); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIndexValidation() { - new SynthesizingMethodParameter(method, 2); + assertThatIllegalArgumentException().isThrownBy(() -> + new SynthesizingMethodParameter(method, 2)); } diff --git a/spring-core/src/test/java/org/springframework/core/codec/AbstractDecoderTestCase.java b/spring-core/src/test/java/org/springframework/core/codec/AbstractDecoderTestCase.java index 4ddd591fe36..99e07518295 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/AbstractDecoderTestCase.java +++ b/spring-core/src/test/java/org/springframework/core/codec/AbstractDecoderTestCase.java @@ -33,7 +33,7 @@ import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MimeType; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Abstract base class for {@link Decoder} unit tests. Subclasses need to implement @@ -208,14 +208,9 @@ public abstract class AbstractDecoderTestCase> protected void testDecodeError(Publisher input, ResolvableType outputType, @Nullable MimeType mimeType, @Nullable Map hints) { - input = Mono.from(input).concatWith(Flux.error(new InputException())); - try { - this.decoder.decode(input, outputType, mimeType, hints).blockLast(Duration.ofSeconds(5)); - fail(); - } - catch (InputException ex) { - // expected - } + Flux buffer = Mono.from(input).concatWith(Flux.error(new InputException())); + assertThatExceptionOfType(InputException.class).isThrownBy(() -> + this.decoder.decode(buffer, outputType, mimeType, hints).blockLast(Duration.ofSeconds(5))); } /** diff --git a/spring-core/src/test/java/org/springframework/core/codec/ResourceDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/ResourceDecoderTests.java index b6dea298b69..213c1b37cd8 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/ResourceDecoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/ResourceDecoderTests.java @@ -34,7 +34,6 @@ import org.springframework.util.StreamUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.core.ResolvableType.forClass; /** @@ -73,8 +72,8 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase + TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0, 2), 2)); } @Test @@ -435,9 +436,10 @@ public class TypeDescriptorTests { assertNull(t1); } - @Test(expected = IllegalArgumentException.class) + @Test public void nestedMethodParameterTypeInvalidNestingLevel() throws Exception { - TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0, 2), 2); + assertThatIllegalArgumentException().isThrownBy(() -> + TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0, 2), 2)); } @Test @@ -684,13 +686,9 @@ public class TypeDescriptorTests { Property property = new Property(getClass(), getClass().getMethod("getProperty"), getClass().getMethod("setProperty", Map.class)); TypeDescriptor typeDescriptor = new TypeDescriptor(property); - try { - typeDescriptor.upcast(Collection.class); - fail("Did not throw"); - } - catch (IllegalArgumentException ex) { - assertEquals("interface java.util.Map is not assignable to interface java.util.Collection", ex.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + typeDescriptor.upcast(Collection.class)) + .withMessage("interface java.util.Map is not assignable to interface java.util.Collection"); } @Test 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 0226fc0d57c..ba793ed5ec5 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,6 +29,7 @@ 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.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -46,25 +47,28 @@ public class ConvertingComparatorTests { private final TestComparator comparator = new TestComparator(); - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowOnNullComparator() throws Exception { - new ConvertingComparator<>(null, this.converter); + assertThatIllegalArgumentException().isThrownBy(() -> + new ConvertingComparator<>(null, this.converter)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowOnNullConverter() throws Exception { - new ConvertingComparator(this.comparator, null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ConvertingComparator(this.comparator, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowOnNullConversionService() throws Exception { - new ConvertingComparator(this.comparator, null, Integer.class); + assertThatIllegalArgumentException().isThrownBy(() -> + new ConvertingComparator(this.comparator, null, Integer.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowOnNullType() throws Exception { - new ConvertingComparator(this.comparator, - this.conversionService, null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ConvertingComparator(this.comparator, this.conversionService, null)); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java b/spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java index c468c863d45..f06d47b81c5 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,6 +56,7 @@ import org.springframework.tests.TestGroup; import org.springframework.util.ClassUtils; import org.springframework.util.StopWatch; +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; @@ -93,9 +94,10 @@ public class DefaultConversionServiceTests { assertEquals(null, conversionService.convert("", Character.class)); } - @Test(expected = ConversionFailedException.class) + @Test public void testStringToCharacterInvalidString() { - conversionService.convert("invalid", Character.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert("invalid", Character.class)); } @Test @@ -130,9 +132,10 @@ public class DefaultConversionServiceTests { assertEquals(null, conversionService.convert("", Boolean.class)); } - @Test(expected = ConversionFailedException.class) + @Test public void testStringToBooleanInvalidString() { - conversionService.convert("invalid", Boolean.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert("invalid", Boolean.class)); } @Test @@ -331,9 +334,10 @@ public class DefaultConversionServiceTests { assertEquals(Long.valueOf(1), conversionService.convert(1, Long.class)); } - @Test(expected = ConversionFailedException.class) + @Test public void testNumberToNumberNotSupportedNumber() { - conversionService.convert(1, CustomNumber.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert(1, CustomNumber.class)); } @Test @@ -397,9 +401,10 @@ public class DefaultConversionServiceTests { assertEquals("3", result.get(2)); } - @Test(expected = ConversionFailedException.class) + @Test public void convertArrayToAbstractCollection() { - conversionService.convert(new String[]{"1", "2", "3"}, AbstractList.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert(new String[]{"1", "2", "3"}, AbstractList.class)); } @Test @@ -881,9 +886,10 @@ public class DefaultConversionServiceTests { assertEquals(ZoneId.of("GMT+1"), conversionService.convert("GMT+1", ZoneId.class)); } - @Test(expected = ConverterNotFoundException.class) + @Test public void convertObjectToObjectNoValueOfMethodOrConstructor() { - conversionService.convert(Long.valueOf(3), SSN.class); + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert(Long.valueOf(3), SSN.class)); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java index 6a9ddbee404..97c01b27f9f 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java @@ -40,6 +40,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -236,22 +237,24 @@ public class CollectionToCollectionConverterTests { assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); } - @Test(expected = ConverterNotFoundException.class) + @Test public void elementTypesNotConvertible() throws Exception { List resources = new ArrayList<>(); resources.add(null); resources.add(null); TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("strings")); - assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); } - @Test(expected = ConversionFailedException.class) + @Test public void nothingInCommon() throws Exception { List resources = new ArrayList<>(); resources.add(new ClassPathResource("test")); resources.add(3); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); - assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java index 1a69c857a14..7cd8c7c1297 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,6 +51,9 @@ 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.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; @@ -59,7 +62,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link GenericConversionService}. @@ -92,14 +94,16 @@ public class GenericConversionServiceTests { assertTrue(conversionService.canConvert(boolean.class, Boolean.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void canConvertFromClassSourceTypeToNullTargetType() { - conversionService.canConvert(String.class, null); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.canConvert(String.class, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void canConvertFromTypeDescriptorSourceTypeToNullTargetType() { - conversionService.canConvert(TypeDescriptor.valueOf(String.class), null); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.canConvert(TypeDescriptor.valueOf(String.class), null)); } @Test @@ -119,19 +123,22 @@ public class GenericConversionServiceTests { assertEquals(null, conversionService.convert(null, Integer.class)); } - @Test(expected = ConversionFailedException.class) + @Test public void convertNullSourcePrimitiveTarget() { - conversionService.convert(null, int.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert(null, int.class)); } - @Test(expected = ConversionFailedException.class) + @Test public void convertNullSourcePrimitiveTargetTypeDescriptor() { - conversionService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class)); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class))); } - @Test(expected = IllegalArgumentException.class) + @Test public void convertNotNullSourceNullSourceTypeDescriptor() { - conversionService.convert("3", null, TypeDescriptor.valueOf(int.class)); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.convert("3", null, TypeDescriptor.valueOf(int.class))); } @Test @@ -140,14 +147,16 @@ public class GenericConversionServiceTests { assertEquals(Boolean.FALSE, conversionService.convert(false, Boolean.class)); } - @Test(expected = ConverterNotFoundException.class) + @Test public void converterNotFound() { - conversionService.convert("3", Integer.class); + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert("3", Integer.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void addConverterNoSourceTargetClassInfoAvailable() { - conversionService.addConverter(new UntypedConverter()); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.addConverter(new UntypedConverter())); } @Test @@ -165,25 +174,29 @@ public class GenericConversionServiceTests { assertNull(conversionService.convert(null, Integer.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void convertToNullTargetClass() { - conversionService.convert("3", (Class) null); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.convert("3", (Class) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void convertToNullTargetTypeDescriptor() { - conversionService.convert("3", TypeDescriptor.valueOf(String.class), null); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.convert("3", TypeDescriptor.valueOf(String.class), null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void convertWrongSourceTypeDescriptor() { - conversionService.convert("3", TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(Long.class)); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.convert("3", TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(Long.class))); } - @Test(expected = ConversionFailedException.class) + @Test public void convertWrongTypeArgument() { conversionService.addConverterFactory(new StringToNumberConverterFactory()); - conversionService.convert("BOGUS", Integer.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> + conversionService.convert("BOGUS", Integer.class)); } @Test @@ -199,10 +212,11 @@ public class GenericConversionServiceTests { } // SPR-8718 - @Test(expected = ConverterNotFoundException.class) + @Test public void convertSuperTarget() { conversionService.addConverter(new ColorConverter()); - conversionService.convert("#000000", SystemColor.class); + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert("#000000", SystemColor.class)); } @Test @@ -226,11 +240,12 @@ public class GenericConversionServiceTests { assertEquals(3, three.intValue()); } - @Test(expected = ConverterNotFoundException.class) + @Test public void genericConverterDelegatingBackToConversionServiceConverterNotFound() { conversionService.addConverter(new ObjectToArrayConverter(conversionService)); assertFalse(conversionService.canConvert(String.class, Integer[].class)); - conversionService.convert("3,4,5", Integer[].class); + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert("3,4,5", Integer[].class)); } @Test @@ -445,14 +460,16 @@ public class GenericConversionServiceTests { assertFalse(pair.hashCode() == pairOpposite.hashCode()); } - @Test(expected = IllegalArgumentException.class) + @Test public void canConvertIllegalArgumentNullTargetTypeFromClass() { - conversionService.canConvert(String.class, null); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.canConvert(String.class, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void canConvertIllegalArgumentNullTargetTypeFromTypeDescriptor() { - conversionService.canConvert(TypeDescriptor.valueOf(String.class), null); + assertThatIllegalArgumentException().isThrownBy(() -> + conversionService.canConvert(TypeDescriptor.valueOf(String.class), null)); } @Test @@ -500,13 +517,9 @@ public class GenericConversionServiceTests { @Test public void shouldNotSupportNullConvertibleTypesFromNonConditionalGenericConverter() { GenericConverter converter = new NonConditionalGenericConverter(); - try { - conversionService.addConverter(converter); - fail("Did not throw IllegalStateException"); - } - catch (IllegalStateException ex) { - assertEquals("Only conditional converters may return null convertible types", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + conversionService.addConverter(converter)) + .withMessage("Only conditional converters may return null convertible types"); } @Test @@ -606,13 +619,8 @@ public class GenericConversionServiceTests { assertEquals(Collections.singleton("testX"), conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); - try { - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection"))); - fail("Should have thrown ConverterNotFoundException"); - } - catch (ConverterNotFoundException ex) { - // expected - } + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))); } @Test 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 c22cb5dd5b7..d1dc5e1a3c7 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,13 +33,13 @@ import org.springframework.core.convert.TypeDescriptor; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +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; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Keith Donald @@ -152,13 +152,8 @@ public class MapToMapConverterTests { TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget")); assertFalse(conversionService.canConvert(sourceType, targetType)); - try { - conversionService.convert(map, sourceType, targetType); - fail("Should have failed"); - } - catch (ConverterNotFoundException ex) { - // expected - } + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + conversionService.convert(map, sourceType, targetType)); conversionService.addConverter(new CollectionToCollectionConverter(conversionService)); conversionService.addConverterFactory(new StringToNumberConverterFactory()); 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 ff6101c6195..aef17995be2 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,6 +22,8 @@ import org.junit.Test; import org.springframework.mock.env.MockPropertySource; +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; @@ -32,7 +34,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Chris Beams @@ -111,13 +112,9 @@ public class MutablePropertySourcesTests { assertThat(sources.size(), equalTo(6)); String bogusPS = "bogus"; - try { - sources.addAfter(bogusPS, new MockPropertySource("h")); - fail("expected non-existent PropertySource exception"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().contains("does not exist")); - } + assertThatIllegalArgumentException().isThrownBy(() -> + sources.addAfter(bogusPS, new MockPropertySource("h"))) + .withMessageContaining("does not exist"); sources.addFirst(new MockPropertySource("a")); assertThat(sources.size(), equalTo(7)); @@ -133,29 +130,17 @@ public class MutablePropertySourcesTests { sources.replace("a-replaced", new MockPropertySource("a")); - try { - sources.replace(bogusPS, new MockPropertySource("bogus-replaced")); - fail("expected non-existent PropertySource exception"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().contains("does not exist")); - } + assertThatIllegalArgumentException().isThrownBy(() -> + sources.replace(bogusPS, new MockPropertySource("bogus-replaced"))) + .withMessageContaining("does not exist"); - try { - sources.addBefore("b", new MockPropertySource("b")); - fail("expected exception"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().contains("cannot be added relative to itself")); - } + assertThatIllegalArgumentException().isThrownBy(() -> + sources.addBefore("b", new MockPropertySource("b"))) + .withMessageContaining("cannot be added relative to itself"); - try { - sources.addAfter("b", new MockPropertySource("b")); - fail("expected exception"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().contains("cannot be added relative to itself")); - } + assertThatIllegalArgumentException().isThrownBy(() -> + sources.addAfter("b", new MockPropertySource("b"))) + .withMessageContaining("cannot be added relative to itself"); } @Test @@ -173,13 +158,8 @@ public class MutablePropertySourcesTests { assertTrue(it.hasNext()); assertEquals("test", it.next().getName()); - try { - it.remove(); - fail("Should have thrown UnsupportedOperationException"); - } - catch (UnsupportedOperationException ex) { - // expected - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( + it::remove); assertFalse(it.hasNext()); } diff --git a/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java b/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java index 6d624e53cf2..809d0572e9d 100644 --- a/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java @@ -29,7 +29,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests for {@link Profiles}. @@ -296,13 +295,9 @@ public class ProfilesTests { } private void assertMalformed(Supplier supplier) { - try { - supplier.get(); - fail("Not malformed"); - } - catch (IllegalArgumentException ex) { - assertTrue(ex.getMessage().contains("Malformed")); - } + assertThatIllegalArgumentException().isThrownBy( + supplier::get) + .withMessageContaining("Malformed"); } private static Predicate activeProfiles(String... profiles) { 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 0b2b2c3b83b..6fc874bba4a 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,13 +26,15 @@ import org.junit.Test; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.mock.env.MockPropertySource; +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; -import static org.junit.Assert.fail; /** * @author Chris Beams @@ -117,13 +119,8 @@ public class PropertySourcesPropertyResolverTests { class TestType { } - try { - propertyResolver.getProperty("foo", TestType.class); - fail("Expected ConverterNotFoundException due to non-convertible types"); - } - catch (ConverterNotFoundException ex) { - // expected - } + assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> + propertyResolver.getProperty("foo", TestType.class)); } @Test @@ -177,13 +174,8 @@ public class PropertySourcesPropertyResolverTests { testProperties.put("exists", "xyz"); assertThat(propertyResolver.getRequiredProperty("exists"), is("xyz")); - try { - propertyResolver.getRequiredProperty("bogus"); - fail("expected IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + propertyResolver.getRequiredProperty("bogus")); } @Test @@ -191,13 +183,8 @@ public class PropertySourcesPropertyResolverTests { testProperties.put("exists", "abc,123"); assertThat(propertyResolver.getRequiredProperty("exists", String[].class), equalTo(new String[] { "abc", "123" })); - try { - propertyResolver.getRequiredProperty("bogus", String[].class); - fail("expected IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + propertyResolver.getRequiredProperty("bogus", String[].class)); } @Test @@ -226,9 +213,10 @@ public class PropertySourcesPropertyResolverTests { equalTo("Replace this value plus defaultValue")); } - @Test(expected = IllegalArgumentException.class) + @Test public void resolvePlaceholders_withNullInput() { - new PropertySourcesPropertyResolver(new MutablePropertySources()).resolvePlaceholders(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new PropertySourcesPropertyResolver(new MutablePropertySources()).resolvePlaceholders(null)); } @Test @@ -239,12 +227,13 @@ public class PropertySourcesPropertyResolverTests { assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key}"), equalTo("Replace this value")); } - @Test(expected = IllegalArgumentException.class) + @Test public void resolveRequiredPlaceholders_withUnresolvable() { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("key", "value")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); - resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown}"); + assertThatIllegalArgumentException().isThrownBy(() -> + resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown}")); } @Test @@ -256,9 +245,10 @@ public class PropertySourcesPropertyResolverTests { equalTo("Replace this value plus defaultValue")); } - @Test(expected = IllegalArgumentException.class) + @Test public void resolveRequiredPlaceholders_withNullInput() { - new PropertySourcesPropertyResolver(new MutablePropertySources()).resolveRequiredPlaceholders(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new PropertySourcesPropertyResolver(new MutablePropertySources()).resolveRequiredPlaceholders(null)); } @Test @@ -270,27 +260,17 @@ public class PropertySourcesPropertyResolverTests { propertyResolver.setRequiredProperties("foo", "bar"); // neither foo nor bar properties are present -> validating should throw - try { - propertyResolver.validateRequiredProperties(); - fail("expected validation exception"); - } - catch (MissingRequiredPropertiesException ex) { - assertThat(ex.getMessage(), equalTo( - "The following properties were declared as required " + - "but could not be resolved: [foo, bar]")); - } + assertThatExceptionOfType(MissingRequiredPropertiesException.class).isThrownBy( + propertyResolver::validateRequiredProperties) + .withMessage("The following properties were declared as required " + + "but could not be resolved: [foo, bar]"); // add foo property -> validation should fail only on missing 'bar' property testProperties.put("foo", "fooValue"); - try { - propertyResolver.validateRequiredProperties(); - fail("expected validation exception"); - } - catch (MissingRequiredPropertiesException ex) { - assertThat(ex.getMessage(), equalTo( - "The following properties were declared as required " + - "but could not be resolved: [bar]")); - } + assertThatExceptionOfType(MissingRequiredPropertiesException.class).isThrownBy( + propertyResolver::validateRequiredProperties) + .withMessage("The following properties were declared as required " + + "but could not be resolved: [bar]"); // add bar property -> validation should pass, even with an empty string value testProperties.put("bar", ""); 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 3516c2758b7..dd5bab2cde2 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,6 +21,8 @@ import java.util.List; import org.junit.Test; +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; @@ -62,28 +64,32 @@ public class SimpleCommandLineParserTests { assertThat(args.getOptionValues("o3"), nullValue()); } - @Test(expected = IllegalArgumentException.class) + @Test public void withEmptyOptionText() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); - parser.parse("--"); + assertThatIllegalArgumentException().isThrownBy(() -> + parser.parse("--")); } - @Test(expected = IllegalArgumentException.class) + @Test public void withEmptyOptionName() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); - parser.parse("--=v1"); + assertThatIllegalArgumentException().isThrownBy(() -> + parser.parse("--=v1")); } - @Test(expected = IllegalArgumentException.class) + @Test public void withEmptyOptionValue() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); - parser.parse("--o1="); + assertThatIllegalArgumentException().isThrownBy(() -> + parser.parse("--o1=")); } - @Test(expected = IllegalArgumentException.class) + @Test public void withEmptyOptionNameAndEmptyOptionValue() { SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); - parser.parse("--="); + assertThatIllegalArgumentException().isThrownBy(() -> + parser.parse("--=")); } @Test @@ -99,16 +105,18 @@ public class SimpleCommandLineParserTests { assertThat(nonOptions.size(), equalTo(2)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void assertOptionNamesIsUnmodifiable() { CommandLineArgs args = new SimpleCommandLineArgsParser().parse(); - args.getOptionNames().add("bogus"); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + args.getOptionNames().add("bogus")); } - @Test(expected = UnsupportedOperationException.class) + @Test public void assertNonOptionArgsIsUnmodifiable() { CommandLineArgs args = new SimpleCommandLineArgsParser().parse(); - args.getNonOptionArgs().add("foo"); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + args.getNonOptionArgs().add("foo")); } } 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 1845b3ef07f..294e2f45fa6 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,6 +28,7 @@ import org.junit.Test; import org.springframework.core.SpringProperties; import org.springframework.mock.env.MockPropertySource; +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; @@ -40,7 +41,6 @@ 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.junit.Assert.fail; import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME; import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME; import static org.springframework.core.env.AbstractEnvironment.RESERVED_DEFAULT_PROFILE_NAME; @@ -144,44 +144,52 @@ public class StandardEnvironmentTests { assertThat(activeProfiles.length, is(2)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setActiveProfiles_withNullProfileArray() { - environment.setActiveProfiles((String[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setActiveProfiles((String[]) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setActiveProfiles_withNullProfile() { - environment.setActiveProfiles((String) null); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setActiveProfiles((String) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setActiveProfiles_withEmptyProfile() { - environment.setActiveProfiles(""); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setActiveProfiles("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void setActiveProfiles_withNotOperator() { - environment.setActiveProfiles("p1", "!p2"); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setActiveProfiles("p1", "!p2")); } - @Test(expected = IllegalArgumentException.class) + @Test public void setDefaultProfiles_withNullProfileArray() { - environment.setDefaultProfiles((String[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setDefaultProfiles((String[]) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setDefaultProfiles_withNullProfile() { - environment.setDefaultProfiles((String) null); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setDefaultProfiles((String) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setDefaultProfiles_withEmptyProfile() { - environment.setDefaultProfiles(""); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setDefaultProfiles("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void setDefaultProfiles_withNotOperator() { - environment.setDefaultProfiles("d1", "!d2"); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.setDefaultProfiles("d1", "!d2")); } @Test @@ -219,11 +227,12 @@ public class StandardEnvironmentTests { System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME); } - @Test(expected = IllegalArgumentException.class) + @Test public void defaultProfileWithCircularPlaceholder() { System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "${spring.profiles.default}"); try { - environment.getDefaultProfiles(); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.getDefaultProfiles()); } finally { System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME); @@ -278,24 +287,28 @@ public class StandardEnvironmentTests { assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItems("pd2", "pd3")); } - @Test(expected = IllegalArgumentException.class) + @Test public void acceptsProfiles_withEmptyArgumentList() { - environment.acceptsProfiles(); + assertThatIllegalArgumentException().isThrownBy( + environment::acceptsProfiles); } - @Test(expected = IllegalArgumentException.class) + @Test public void acceptsProfiles_withNullArgumentList() { - environment.acceptsProfiles((String[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.acceptsProfiles((String[]) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void acceptsProfiles_withNullArgument() { - environment.acceptsProfiles((String) null); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.acceptsProfiles((String) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void acceptsProfiles_withEmptyArgument() { - environment.acceptsProfiles(""); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.acceptsProfiles("")); } @Test @@ -335,9 +348,10 @@ public class StandardEnvironmentTests { assertThat(environment.acceptsProfiles("!p1"), is(false)); } - @Test(expected = IllegalArgumentException.class) + @Test public void acceptsProfiles_withInvalidNotOperator() { - environment.acceptsProfiles("p1", "!"); + assertThatIllegalArgumentException().isThrownBy(() -> + environment.acceptsProfiles("p1", "!")); } @Test @@ -364,14 +378,9 @@ public class StandardEnvironmentTests { env.addActiveProfile("validProfile"); // succeeds - try { - env.addActiveProfile("invalid-profile"); - fail("expected validation exception"); - } - catch (IllegalArgumentException ex) { - assertThat(ex.getMessage(), - equalTo("Invalid profile [invalid-profile]: must not contain dash character")); - } + assertThatIllegalArgumentException().isThrownBy(() -> + env.addActiveProfile("invalid-profile")) + .withMessage("Invalid profile [invalid-profile]: must not contain dash character"); } @Test @@ -454,13 +463,8 @@ public class StandardEnvironmentTests { // the user that under these very special conditions (non-object key + // SecurityManager that disallows access to system properties), they // cannot do what they're attempting. - try { - systemProperties.get(NON_STRING_PROPERTY_NAME); - fail("Expected IllegalArgumentException when searching with non-string key against ReadOnlySystemAttributesMap"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().as("searching with non-string key against ReadOnlySystemAttributesMap").isThrownBy(() -> + systemProperties.get(NON_STRING_PROPERTY_NAME)); } System.setSecurityManager(oldSecurityManager); diff --git a/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java index 76bb8ee27d4..dda86815e51 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java @@ -17,19 +17,15 @@ package org.springframework.core.io; import java.io.FileNotFoundException; -import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests that serve as regression tests for the bugs described in SPR-6888 @@ -136,14 +132,9 @@ public class ClassPathResourceTests { } private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { - try { - resource.getInputStream(); - fail("FileNotFoundException expected for resource: " + resource); - } - catch (IOException ex) { - assertThat(ex, instanceOf(FileNotFoundException.class)); - assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH)); - } + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( + resource::getInputStream) + .withMessageContaining(FQ_RESOURCE_PATH); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java index 3063b595246..491875ed3a6 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java @@ -22,6 +22,7 @@ import org.junit.Test; import org.springframework.core.env.StandardEnvironment; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -44,9 +45,10 @@ public class ResourceEditorTests { assertTrue(resource.exists()); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorWithNullCtorArgs() throws Exception { - new ResourceEditor(null, null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ResourceEditor(null, null)); } @Test @@ -77,14 +79,15 @@ public class ResourceEditorTests { } } - @Test(expected = IllegalArgumentException.class) + @Test public void testStrictSystemPropertyReplacement() { PropertyEditor editor = new ResourceEditor(new DefaultResourceLoader(), new StandardEnvironment(), false); System.setProperty("test.prop", "foo"); try { - editor.setAsText("${test.prop}-${bar}"); - Resource resolved = (Resource) editor.getValue(); - assertEquals("foo-${bar}", resolved.getFilename()); + assertThatIllegalArgumentException().isThrownBy(() -> { + editor.setAsText("${test.prop}-${bar}"); + editor.getValue(); + }); } finally { System.getProperties().remove("test.prop"); diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java index 3e4e0e33438..e1bde2fd342 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,13 +32,13 @@ import org.junit.Test; import org.springframework.util.FileCopyUtils; +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; -import static org.junit.Assert.fail; /** * Unit tests for various {@link Resource} implementations. @@ -197,20 +197,10 @@ public class ResourceTests { Resource relative4 = resource.createRelative("X.class"); assertFalse(relative4.exists()); assertFalse(relative4.isReadable()); - try { - relative4.contentLength(); - fail("Should have thrown FileNotFoundException"); - } - catch (FileNotFoundException ex) { - // expected - } - try { - relative4.lastModified(); - fail("Should have thrown FileNotFoundException"); - } - catch (FileNotFoundException ex) { - // expected - } + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( + relative4::contentLength); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( + relative4::lastModified); } @Test @@ -255,27 +245,15 @@ public class ResourceTests { } }; - try { - resource.getURL(); - fail("FileNotFoundException should have been thrown"); - } - catch (FileNotFoundException ex) { - assertTrue(ex.getMessage().contains(name)); - } - try { - resource.getFile(); - fail("FileNotFoundException should have been thrown"); - } - catch (FileNotFoundException ex) { - assertTrue(ex.getMessage().contains(name)); - } - try { - resource.createRelative("/testing"); - fail("FileNotFoundException should have been thrown"); - } - catch (FileNotFoundException ex) { - assertTrue(ex.getMessage().contains(name)); - } + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( + resource::getURL) + .withMessageContaining(name); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( + resource::getFile) + .withMessageContaining(name); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + resource.createRelative("/testing")) + .withMessageContaining(name); assertThat(resource.getFilename(), nullValue()); } @@ -313,24 +291,28 @@ public class ResourceTests { } } - @Test(expected = FileNotFoundException.class) + @Test public void testInputStreamNotFoundOnFileSystemResource() throws IOException { - new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").getInputStream(); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").getInputStream()); } - @Test(expected = FileNotFoundException.class) + @Test public void testReadableChannelNotFoundOnFileSystemResource() throws IOException { - new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").readableChannel(); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").readableChannel()); } - @Test(expected = FileNotFoundException.class) + @Test public void testInputStreamNotFoundOnClassPathResource() throws IOException { - new ClassPathResource("Resource.class", getClass()).createRelative("X").getInputStream(); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + new ClassPathResource("Resource.class", getClass()).createRelative("X").getInputStream()); } - @Test(expected = FileNotFoundException.class) + @Test public void testReadableChannelNotFoundOnClassPathResource() throws IOException { - new ClassPathResource("Resource.class", getClass()).createRelative("X").readableChannel(); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + new ClassPathResource("Resource.class", getClass()).createRelative("X").readableChannel()); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java index 1330cd506a0..3baeb23e2bf 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java @@ -25,10 +25,11 @@ import java.util.Arrays; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Arjen Poutsma @@ -80,10 +81,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void readPositionSmallerThanZero() { DataBuffer buffer = createDataBuffer(1); try { - buffer.readPosition(-1); - fail("IndexOutOfBoundsException expected"); - } - catch (IndexOutOfBoundsException ignored) { + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> + buffer.readPosition(-1)); } finally { release(buffer); @@ -94,10 +93,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void readPositionGreaterThanWritePosition() { DataBuffer buffer = createDataBuffer(1); try { - buffer.readPosition(1); - fail("IndexOutOfBoundsException expected"); - } - catch (IndexOutOfBoundsException ignored) { + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> + buffer.readPosition(1)); } finally { release(buffer); @@ -110,11 +107,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { try { buffer.write((byte) 'a'); buffer.read(); - - buffer.writePosition(0); - fail("IndexOutOfBoundsException expected"); - } - catch (IndexOutOfBoundsException ignored) { + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> + buffer.writePosition(0)); } finally { release(buffer); @@ -125,10 +119,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void writePositionGreaterThanCapacity() { DataBuffer buffer = createDataBuffer(1); try { - buffer.writePosition(2); - fail("IndexOutOfBoundsException expected"); - } - catch (IndexOutOfBoundsException ignored) { + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> + buffer.writePosition(2)); } finally { release(buffer); @@ -158,10 +150,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void writeNullString() { DataBuffer buffer = createDataBuffer(1); try { - buffer.write(null, StandardCharsets.UTF_8); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException exc) { + assertThatIllegalArgumentException().isThrownBy(() -> + buffer.write(null, StandardCharsets.UTF_8)); } finally { release(buffer); @@ -172,10 +162,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void writeNullCharset() { DataBuffer buffer = createDataBuffer(1); try { - buffer.write("test", null); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException exc) { + assertThatIllegalArgumentException().isThrownBy(() -> + buffer.write("test", null)); } finally { release(buffer); @@ -369,10 +357,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void capacityLessThanZero() { DataBuffer buffer = createDataBuffer(1); try { - buffer.capacity(-1); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ignored) { + assertThatIllegalArgumentException().isThrownBy(() -> + buffer.capacity(-1)); } finally { release(buffer); @@ -558,12 +544,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { DataBuffer slice = buffer.slice(1, 2); assertEquals(2, slice.readableByteCount()); - try { - slice.write((byte) 0); - fail("Exception expected"); - } - catch (Exception ignored) { - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + slice.write((byte) 0)); buffer.write((byte) 'c'); assertEquals(3, buffer.readableByteCount()); @@ -589,12 +571,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { DataBuffer slice = buffer.retainedSlice(1, 2); assertEquals(2, slice.readableByteCount()); - try { - slice.write((byte) 0); - fail("Exception expected"); - } - catch (Exception ignored) { - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + slice.write((byte) 0)); buffer.write((byte) 'c'); assertEquals(3, buffer.readableByteCount()); @@ -651,19 +629,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { assertEquals('a', buffer.getByte(0)); assertEquals('b', buffer.getByte(1)); assertEquals('c', buffer.getByte(2)); - try { - buffer.getByte(-1); - fail("IndexOutOfBoundsException expected"); - } - catch (IndexOutOfBoundsException ignored) { - } + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> + buffer.getByte(-1)); - try { - buffer.getByte(3); - fail("IndexOutOfBoundsException expected"); - } - catch (IndexOutOfBoundsException ignored) { - } + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> + buffer.getByte(3)); release(buffer); } diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java index 71fe5a9cc69..ed943c0c934 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java @@ -49,7 +49,6 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.buffer.support.DataBufferTestUtils; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.isA; @@ -489,17 +488,17 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { DataBufferUtils.write(sourceFlux, channel) .subscribe(DataBufferUtils.releaseConsumer(), - throwable -> fail(throwable.getMessage()), + throwable -> { + throw new AssertionError(throwable.getMessage(), throwable); + }, () -> { try { String expected = String.join("", Files.readAllLines(source)); String result = String.join("", Files.readAllLines(destination)); - assertEquals(expected, result); - } catch (IOException e) { - fail(e.getMessage()); + throw new AssertionError(e.getMessage(), e); } finally { DataBufferUtils.closeChannel(channel); @@ -523,7 +522,9 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { DataBufferUtils.write(sourceFlux, channel) .subscribe(DataBufferUtils::release, - throwable -> fail(throwable.getMessage()), + throwable -> { + throw new AssertionError(throwable.getMessage(), throwable); + }, () -> { try { String expected = String.join("", Files.readAllLines(source)); @@ -534,7 +535,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { } catch (IOException e) { - fail(e.getMessage()); + throw new AssertionError(e.getMessage(), e); } finally { DataBufferUtils.closeChannel(channel); diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java index 38d7f34c842..9fe4f0821a3 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java @@ -18,7 +18,7 @@ package org.springframework.core.io.buffer; import org.junit.Test; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.core.io.buffer.DataBufferUtils.release; /** @@ -33,11 +33,8 @@ public class LeakAwareDataBufferFactoryTests { public void leak() { DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(); try { - this.bufferFactory.checkForLeaks(); - fail("AssertionError expected"); - } - catch (AssertionError expected) { - // ignore + assertThatExceptionOfType(AssertionError.class).isThrownBy( + this.bufferFactory::checkForLeaks); } finally { release(dataBuffer); diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java index ff37f0a2176..f24005d7af7 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java @@ -22,6 +22,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -60,13 +61,14 @@ public class PooledDataBufferTests { assertTrue(result); } - @Test(expected = IllegalStateException.class) + @Test public void tooManyReleases() { PooledDataBuffer buffer = createDataBuffer(1); buffer.write((byte) 'a'); buffer.release(); - buffer.release(); + assertThatIllegalStateException().isThrownBy( + buffer::release); } diff --git a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java index ca6b0bf4c1c..c02123bad94 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java @@ -28,6 +28,7 @@ import org.junit.Test; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -58,9 +59,10 @@ public class PathMatchingResourcePatternResolverTests { private PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - @Test(expected = FileNotFoundException.class) + @Test public void invalidPrefixWithPatternElementInIt() throws IOException { - resolver.getResources("xx**:**/*.xy"); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> + resolver.getResources("xx**:**/*.xy")); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java b/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java index ba4c610ca21..559cd7b5d52 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -69,16 +70,15 @@ public class ResourceArrayPropertyEditorTests { } } - @Test(expected = IllegalArgumentException.class) + @Test public void testStrictSystemPropertyReplacement() { PropertyEditor editor = new ResourceArrayPropertyEditor( new PathMatchingResourcePatternResolver(), new StandardEnvironment(), false); System.setProperty("test.prop", "foo"); try { - editor.setAsText("${test.prop}-${bar}"); - Resource[] resources = (Resource[]) editor.getValue(); - assertEquals("foo-${bar}", resources[0].getFilename()); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText("${test.prop}-${bar}")); } finally { System.getProperties().remove("test.prop"); diff --git a/spring-core/src/test/java/org/springframework/core/io/support/ResourceRegionTests.java b/spring-core/src/test/java/org/springframework/core/io/support/ResourceRegionTests.java index 2ff621bc124..519aa3da641 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/ResourceRegionTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/ResourceRegionTests.java @@ -20,6 +20,7 @@ import org.junit.Test; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -29,19 +30,22 @@ import static org.mockito.Mockito.mock; */ public class ResourceRegionTests { - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowExceptionWithNullResource() { - new ResourceRegion(null, 0, 1); + assertThatIllegalArgumentException().isThrownBy(() -> + new ResourceRegion(null, 0, 1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowExceptionForNegativePosition() { - new ResourceRegion(mock(Resource.class), -1, 1); + assertThatIllegalArgumentException().isThrownBy(() -> + new ResourceRegion(mock(Resource.class), -1, 1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowExceptionForNegativeCount() { - new ResourceRegion(mock(Resource.class), 0, -1); + assertThatIllegalArgumentException().isThrownBy(() -> + new ResourceRegion(mock(Resource.class), 0, -1)); } } diff --git a/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java b/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java index d293f5d733e..49b534b55f7 100644 --- a/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java @@ -25,10 +25,8 @@ import org.springframework.core.serializer.support.DeserializingConverter; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.core.serializer.support.SerializingConverter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Gary Russell @@ -48,33 +46,24 @@ public class SerializationConverterTests { @Test public void nonSerializableObject() { SerializingConverter toBytes = new SerializingConverter(); - try { - toBytes.convert(new Object()); - fail("Expected IllegalArgumentException"); - } - catch (SerializationFailedException e) { - assertNotNull(e.getCause()); - assertTrue(e.getCause() instanceof IllegalArgumentException); - } + assertThatExceptionOfType(SerializationFailedException.class).isThrownBy(() -> + toBytes.convert(new Object())) + .withCauseInstanceOf(IllegalArgumentException.class); } @Test public void nonSerializableField() { SerializingConverter toBytes = new SerializingConverter(); - try { - toBytes.convert(new UnSerializable()); - fail("Expected SerializationFailureException"); - } - catch (SerializationFailedException e) { - assertNotNull(e.getCause()); - assertTrue(e.getCause() instanceof NotSerializableException); - } + assertThatExceptionOfType(SerializationFailedException.class).isThrownBy(() -> + toBytes.convert(new UnSerializable())) + .withCauseInstanceOf(NotSerializableException.class); } - @Test(expected = SerializationFailedException.class) + @Test public void deserializationFailure() { DeserializingConverter fromBytes = new DeserializingConverter(); - fromBytes.convert("Junk".getBytes()); + assertThatExceptionOfType(SerializationFailedException.class).isThrownBy(() -> + fromBytes.convert("Junk".getBytes())); } diff --git a/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java b/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java index 1a87ec41aef..6f519579d77 100644 --- a/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java +++ b/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java @@ -23,10 +23,12 @@ import java.util.NoSuchElementException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** @@ -41,13 +43,8 @@ public class CompositeIteratorTests { public void testNoIterators() { CompositeIterator it = new CompositeIterator<>(); assertFalse(it.hasNext()); - try { - it.next(); - fail(); - } - catch (NoSuchElementException ex) { - // expected - } + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( + it::next); } @Test @@ -59,13 +56,8 @@ public class CompositeIteratorTests { assertEquals(String.valueOf(i), it.next()); } assertFalse(it.hasNext()); - try { - it.next(); - fail(); - } - catch (NoSuchElementException ex) { - // expected - } + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( + it::next); } @Test @@ -79,13 +71,9 @@ public class CompositeIteratorTests { assertEquals(String.valueOf(i), it.next()); } assertFalse(it.hasNext()); - try { - it.next(); - fail(); - } - catch (NoSuchElementException ex) { - // expected - } + + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( + it::next); } @Test @@ -94,23 +82,13 @@ public class CompositeIteratorTests { CompositeIterator it = new CompositeIterator<>(); it.add(list.iterator()); it.hasNext(); - try { - it.add(list.iterator()); - fail(); - } - catch (IllegalStateException ex) { - // expected - } - it = new CompositeIterator<>(); - it.add(list.iterator()); - it.next(); - try { - it.add(list.iterator()); - fail(); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + it.add(list.iterator())); + CompositeIterator it2 = new CompositeIterator<>(); + it2.add(list.iterator()); + it2.next(); + assertThatIllegalStateException().isThrownBy(() -> + it2.add(list.iterator())); } @Test @@ -120,13 +98,8 @@ public class CompositeIteratorTests { CompositeIterator it = new CompositeIterator<>(); it.add(iterator); it.add(list.iterator()); - try { - it.add(iterator); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + it.add(iterator)); } } diff --git a/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java b/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java index ba354dee790..295d0e4e2cc 100644 --- a/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java +++ b/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java @@ -24,6 +24,8 @@ import java.nio.charset.StandardCharsets; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIOException; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -84,10 +86,11 @@ public class FastByteArrayOutputStreamTests { assertByteArrayEqualsString(this.os); } - @Test(expected = IOException.class) + @Test public void close() throws Exception { this.os.close(); - this.os.write(this.helloBytes); + assertThatIOException().isThrownBy(() -> + this.os.write(this.helloBytes)); } @Test @@ -107,10 +110,11 @@ public class FastByteArrayOutputStreamTests { assertArrayEquals(baos.toByteArray(), this.helloBytes); } - @Test(expected = IllegalArgumentException.class) + @Test public void failResize() throws Exception { this.os.write(this.helloBytes); - this.os.resize(5); + assertThatIllegalArgumentException().isThrownBy(() -> + this.os.resize(5)); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java b/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java index d60975e5570..f6bd6a770fb 100644 --- a/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java +++ b/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java @@ -28,6 +28,8 @@ import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -44,34 +46,40 @@ import static org.junit.Assert.assertTrue; */ public class MimeTypeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void slashInSubtype() { - new MimeType("text", "/"); + assertThatIllegalArgumentException().isThrownBy(() -> + new MimeType("text", "/")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void valueOfNoSubtype() { - MimeType.valueOf("audio"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeType.valueOf("audio")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void valueOfNoSubtypeSlash() { - MimeType.valueOf("audio/"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeType.valueOf("audio/")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void valueOfIllegalType() { - MimeType.valueOf("audio(/basic"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeType.valueOf("audio(/basic")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void valueOfIllegalSubtype() { - MimeType.valueOf("audio/basic)"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeType.valueOf("audio/basic)")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void valueOfIllegalCharset() { - MimeType.valueOf("text/html; charset=foo-bar"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeType.valueOf("text/html; charset=foo-bar")); } @Test @@ -185,59 +193,70 @@ public class MimeTypeTests { assertEquals("Invalid subtype", "*", mimeType.getSubtype()); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeNoSubtype() { - MimeTypeUtils.parseMimeType("audio"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeNoSubtypeSlash() { - MimeTypeUtils.parseMimeType("audio/"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeTypeRange() { - MimeTypeUtils.parseMimeType("*/json"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("*/json")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeIllegalType() { - MimeTypeUtils.parseMimeType("audio(/basic"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio(/basic")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeIllegalSubtype() { - MimeTypeUtils.parseMimeType("audio/basic)"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/basic)")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeMissingTypeAndSubtype() { - MimeTypeUtils.parseMimeType(" ;a=b"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType(" ;a=b")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeEmptyParameterAttribute() { - MimeTypeUtils.parseMimeType("audio/*;=value"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/*;=value")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeEmptyParameterValue() { - MimeTypeUtils.parseMimeType("audio/*;attr="); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/*;attr=")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeIllegalParameterAttribute() { - MimeTypeUtils.parseMimeType("audio/*;attr<=value"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/*;attr<=value")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeIllegalParameterValue() { - MimeTypeUtils.parseMimeType("audio/*;attr=v>alue"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/*;attr=v>alue")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeIllegalCharset() { - MimeTypeUtils.parseMimeType("text/html; charset=foo-bar"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("text/html; charset=foo-bar")); } @Test // SPR-8917 @@ -264,9 +283,10 @@ public class MimeTypeTests { assertEquals("\" bar \"", mimeType.getParameter("foo")); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void parseMimeTypeIllegalQuotedParameterValue() { - MimeTypeUtils.parseMimeType("audio/*;attr=\""); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + MimeTypeUtils.parseMimeType("audio/*;attr=\"")); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java b/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java index bb13de03723..4baf587b2e4 100644 --- a/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java @@ -23,9 +23,8 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -204,26 +203,14 @@ public class NumberUtilsTests { String aLong = "" + Long.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; - try { - NumberUtils.parseNumber(aLong, Byte.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Byte.class)); - try { - NumberUtils.parseNumber(aLong, Short.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Short.class)); - try { - NumberUtils.parseNumber(aLong, Integer.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Integer.class)); assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class)); assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class)); @@ -234,26 +221,14 @@ public class NumberUtilsTests { String aLong = "" + Long.MIN_VALUE; String aDouble = "" + Double.MIN_VALUE; - try { - NumberUtils.parseNumber(aLong, Byte.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Byte.class)); - try { - NumberUtils.parseNumber(aLong, Short.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Short.class)); - try { - NumberUtils.parseNumber(aLong, Integer.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Integer.class)); assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class)); assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class)); @@ -265,26 +240,14 @@ public class NumberUtilsTests { String aLong = "" + Long.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; - try { - NumberUtils.parseNumber(aLong, Byte.class, nf); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Byte.class, nf)); - try { - NumberUtils.parseNumber(aLong, Short.class, nf); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Short.class, nf)); - try { - NumberUtils.parseNumber(aLong, Integer.class, nf); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Integer.class, nf)); assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf)); assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf)); @@ -296,26 +259,14 @@ public class NumberUtilsTests { String aLong = "" + Long.MIN_VALUE; String aDouble = "" + Double.MIN_VALUE; - try { - NumberUtils.parseNumber(aLong, Byte.class, nf); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Byte.class, nf)); - try { - NumberUtils.parseNumber(aLong, Short.class, nf); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Short.class, nf)); - try { - NumberUtils.parseNumber(aLong, Integer.class, nf); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> + NumberUtils.parseNumber(aLong, Integer.class, nf)); assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf)); assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf)); @@ -451,15 +402,10 @@ public class NumberUtilsTests { } private void assertToNumberOverflow(Number number, Class targetClass) { - String msg = "Expected exception due to overflow: from=" + number + ", toClass=" + targetClass; - try { - NumberUtils.convertNumberToTargetClass(number, targetClass); - fail(msg); - } - catch (IllegalArgumentException expected) { - assertTrue(msg + ", with \"overflow\" in message but got message=" + expected.getMessage(), - expected.getMessage().endsWith("overflow")); - } + String msg = "overflow: from=" + number + ", toClass=" + targetClass; + assertThatIllegalArgumentException().as(msg).isThrownBy(() -> + NumberUtils.convertNumberToTargetClass(number, targetClass)) + .withMessageEndingWith("overflow"); } } diff --git a/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java b/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java index d6e26594b12..9c59596695a 100644 --- a/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java +++ b/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java @@ -20,6 +20,7 @@ import java.util.Properties; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -104,14 +105,15 @@ public class PropertyPlaceholderHelperTests { assertEquals("foo=bar,bar=${bar}", this.helper.replacePlaceholders(text, props)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testUnresolvedPlaceholderAsError() { String text = "foo=${foo},bar=${bar}"; Properties props = new Properties(); props.setProperty("foo", "bar"); PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}", null, false); - assertEquals("foo=bar,bar=${bar}", helper.replacePlaceholders(text, props)); + assertThatIllegalArgumentException().isThrownBy(() -> + helper.replacePlaceholders(text, props)); } } 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 34f2b9ed438..943b1f6873d 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -32,6 +32,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.tests.sample.objects.TestObject; +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; @@ -119,25 +120,28 @@ public class ReflectionUtilsTests { assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void copySrcToDestinationOfIncorrectClass() { TestObject src = new TestObject(); String dest = new String(); - ReflectionUtils.shallowCopyFieldState(src, dest); + assertThatIllegalArgumentException().isThrownBy(() -> + ReflectionUtils.shallowCopyFieldState(src, dest)); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsNullSrc() { TestObject src = null; String dest = new String(); - ReflectionUtils.shallowCopyFieldState(src, dest); + assertThatIllegalArgumentException().isThrownBy(() -> + ReflectionUtils.shallowCopyFieldState(src, dest)); } - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsNullDest() { TestObject src = new TestObject(); String dest = null; - ReflectionUtils.shallowCopyFieldState(src, dest); + assertThatIllegalArgumentException().isThrownBy(() -> + ReflectionUtils.shallowCopyFieldState(src, dest)); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java b/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java index 4209a240c8c..34349f93e47 100644 --- a/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java +++ b/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java @@ -19,6 +19,7 @@ package org.springframework.util; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -76,10 +77,11 @@ public class ResizableByteArrayOutputStreamTests { assertByteArrayEqualsString(this.baos); } - @Test(expected = IllegalArgumentException.class) + @Test public void failResize() throws Exception{ this.baos.write(helloBytes); - this.baos.resize(5); + assertThatIllegalArgumentException().isThrownBy(() -> + this.baos.resize(5)); } diff --git a/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java index 9524580913f..35b2399f8fe 100644 --- a/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java @@ -20,8 +20,9 @@ import java.math.BigInteger; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** @@ -42,21 +43,23 @@ public class SerializationUtilsTests { assertEquals("foo", SerializationUtils.deserialize(SerializationUtils.serialize("foo"))); } - @Test(expected = IllegalStateException.class) + @Test public void deserializeUndefined() throws Exception { byte[] bytes = FOO.toByteArray(); - Object foo = SerializationUtils.deserialize(bytes); - assertNotNull(foo); + assertThatIllegalStateException().isThrownBy(() -> + SerializationUtils.deserialize(bytes)); } - @Test(expected = IllegalArgumentException.class) + @Test public void serializeNonSerializable() throws Exception { - SerializationUtils.serialize(new Object()); + assertThatIllegalArgumentException().isThrownBy(() -> + SerializationUtils.serialize(new Object())); } - @Test(expected = IllegalArgumentException.class) + @Test public void deserializeNonSerializable() throws Exception { - SerializationUtils.deserialize("foo".getBytes()); + assertThatIllegalArgumentException().isThrownBy(() -> + SerializationUtils.deserialize("foo".getBytes())); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java index 1f6937e1fd0..387d35dde7e 100644 --- a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java @@ -22,6 +22,7 @@ import java.util.Properties; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -29,7 +30,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -718,13 +718,8 @@ public class StringUtilsTests { @Test // SPR-7779 public void testParseLocaleWithInvalidCharacters() { - try { - StringUtils.parseLocaleString("%0D%0AContent-length:30%0D%0A%0D%0A%3Cscript%3Ealert%28123%29%3C/script%3E"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + StringUtils.parseLocaleString("%0D%0AContent-length:30%0D%0A%0D%0A%3Cscript%3Ealert%28123%29%3C/script%3E")); } @Test // SPR-9420 diff --git a/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java index 25ffcae475e..3bc89ab1171 100644 --- a/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java @@ -20,6 +20,7 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -94,10 +95,10 @@ public class SystemPropertyUtilsTests { assertEquals("Y#{foo.bar}X", resolved); } - @Test(expected = IllegalArgumentException.class) + @Test public void testReplaceWithNoDefault() { - String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop}"); - assertEquals("", resolved); + assertThatIllegalArgumentException().isThrownBy(() -> + SystemPropertyUtils.resolvePlaceholders("${test.prop}")); } @Test 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 5813664867a..25c6e653e27 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,6 +20,7 @@ import java.util.Comparator; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -36,14 +37,16 @@ public class InvertibleComparatorTests { private final Comparator comparator = new ComparableComparator<>(); - @Test(expected = IllegalArgumentException.class) + @Test public void shouldNeedComparator() throws Exception { - new InvertibleComparator<>(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new InvertibleComparator<>(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldNeedComparatorWithAscending() throws Exception { - new InvertibleComparator<>(null, true); + assertThatIllegalArgumentException().isThrownBy(() -> + new InvertibleComparator<>(null, true)); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java b/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java index 109b2ac163f..cfb263754c8 100644 --- a/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java +++ b/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java @@ -22,6 +22,8 @@ import java.util.concurrent.ExecutionException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; @@ -49,7 +51,7 @@ public class ListenableFutureTaskTests { } @Override public void onFailure(Throwable ex) { - fail(ex.getMessage()); + throw new AssertionError(ex.getMessage(), ex); } }); task.run(); @@ -79,20 +81,12 @@ public class ListenableFutureTaskTests { }); task.run(); - try { - task.get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertSame(s, ex.getCause().getMessage()); - } - try { - task.completable().get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex) { - assertSame(s, ex.getCause().getMessage()); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + task::get) + .satisfies(ex -> assertThat(ex.getCause().getMessage()).isEqualTo(s)); + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + task.completable()::get) + .satisfies(ex -> assertThat(ex.getCause().getMessage()).isEqualTo(s)); } @Test @@ -129,20 +123,12 @@ public class ListenableFutureTaskTests { verify(failureCallback).onFailure(ex); verifyZeroInteractions(successCallback); - try { - task.get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex2) { - assertSame(s, ex2.getCause().getMessage()); - } - try { - task.completable().get(); - fail("Should have thrown ExecutionException"); - } - catch (ExecutionException ex2) { - assertSame(s, ex2.getCause().getMessage()); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + task::get) + .satisfies(e -> assertThat(e.getCause().getMessage()).isEqualTo(s)); + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + task.completable()::get) + .satisfies(e -> assertThat(e.getCause().getMessage()).isEqualTo(s)); } } 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 77462945014..c8abc66b1f3 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,6 +24,7 @@ import java.util.concurrent.TimeoutException; import org.junit.Test; +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; @@ -81,13 +82,9 @@ public class SettableListenableFutureTests { Throwable exception = new RuntimeException(); assertTrue(settableListenableFuture.setException(exception)); - try { - settableListenableFuture.get(); - fail("Expected ExecutionException"); - } - catch (ExecutionException ex) { - assertThat(ex.getCause(), equalTo(exception)); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + settableListenableFuture::get) + .withCause(exception); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); @@ -99,13 +96,9 @@ public class SettableListenableFutureTests { assertTrue(settableListenableFuture.setException(exception)); Future completable = settableListenableFuture.completable(); - try { - completable.get(); - fail("Expected ExecutionException"); - } - catch (ExecutionException ex) { - assertThat(ex.getCause(), equalTo(exception)); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + completable::get) + .withCause(exception); assertFalse(completable.isCancelled()); assertTrue(completable.isDone()); @@ -116,13 +109,9 @@ public class SettableListenableFutureTests { Throwable exception = new OutOfMemoryError(); assertTrue(settableListenableFuture.setException(exception)); - try { - settableListenableFuture.get(); - fail("Expected ExecutionException"); - } - catch (ExecutionException ex) { - assertThat(ex.getCause(), equalTo(exception)); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + settableListenableFuture::get) + .withCause(exception); assertFalse(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); @@ -134,13 +123,9 @@ public class SettableListenableFutureTests { assertTrue(settableListenableFuture.setException(exception)); Future completable = settableListenableFuture.completable(); - try { - completable.get(); - fail("Expected ExecutionException"); - } - catch (ExecutionException ex) { - assertThat(ex.getCause(), equalTo(exception)); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy( + completable::get) + .withCause(exception); assertFalse(completable.isCancelled()); assertTrue(completable.isDone()); @@ -158,7 +143,7 @@ public class SettableListenableFutureTests { } @Override public void onFailure(Throwable ex) { - fail("Expected onSuccess() to be called"); + throw new AssertionError("Expected onSuccess() to be called", ex); } }); @@ -180,7 +165,7 @@ public class SettableListenableFutureTests { } @Override public void onFailure(Throwable ex) { - fail("Expected onSuccess() to be called"); + throw new AssertionError("Expected onSuccess() to be called", ex); } }); @@ -269,13 +254,8 @@ public class SettableListenableFutureTests { @Test public void getWithTimeoutThrowsTimeoutException() throws ExecutionException, InterruptedException { - try { - settableListenableFuture.get(1L, TimeUnit.MILLISECONDS); - fail("Expected TimeoutException"); - } - catch (TimeoutException ex) { - // expected - } + assertThatExceptionOfType(TimeoutException.class).isThrownBy(() -> + settableListenableFuture.get(1L, TimeUnit.MILLISECONDS)); } @Test @@ -362,13 +342,8 @@ public class SettableListenableFutureTests { public void cancelStateThrowsExceptionWhenCallingGet() throws ExecutionException, InterruptedException { settableListenableFuture.cancel(true); - try { - settableListenableFuture.get(); - fail("Expected CancellationException"); - } - catch (CancellationException ex) { - // expected - } + assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> + settableListenableFuture.get()); assertTrue(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); @@ -389,13 +364,8 @@ public class SettableListenableFutureTests { } }).start(); - try { - settableListenableFuture.get(500L, TimeUnit.MILLISECONDS); - fail("Expected CancellationException"); - } - catch (CancellationException ex) { - // expected - } + assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> + settableListenableFuture.get(500L, TimeUnit.MILLISECONDS)); assertTrue(settableListenableFuture.isCancelled()); assertTrue(settableListenableFuture.isDone()); 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 6885640ba08..356875abe31 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 @@ -33,10 +33,9 @@ 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.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; /** @@ -88,14 +87,9 @@ public class ListBasedXMLEventReaderTests { assertEquals(START_DOCUMENT, reader.nextEvent().getEventType()); - try { - reader.getElementText(); - fail("Should have thrown XMLStreamException"); - } - catch (XMLStreamException ex) { - // expected - assertTrue(ex.getMessage().startsWith("Not at START_ELEMENT")); - } + assertThatExceptionOfType(XMLStreamException.class).isThrownBy( + reader::getElementText) + .withMessageStartingWith("Not at START_ELEMENT"); } private List readEvents(String xml) throws XMLStreamException { 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 8a2c0aa6da9..0470d5741b9 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 @@ -23,6 +23,8 @@ import javax.xml.XMLConstants; import org.junit.Test; +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; @@ -45,9 +47,10 @@ public class SimpleNamespaceContextTests { private final SimpleNamespaceContext context = new SimpleNamespaceContext(); - @Test(expected = IllegalArgumentException.class) + @Test public void getNamespaceURI_withNull() throws Exception { - context.getNamespaceURI(null); + assertThatIllegalArgumentException().isThrownBy(() -> + context.getNamespaceURI(null)); } @Test @@ -72,9 +75,10 @@ public class SimpleNamespaceContextTests { context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX), is(defaultNamespaceUri)); } - @Test(expected = IllegalArgumentException.class) + @Test public void getPrefix_withNull() throws Exception { - context.getPrefix(null); + assertThatIllegalArgumentException().isThrownBy(() -> + context.getPrefix(null)); } @Test @@ -92,16 +96,18 @@ public class SimpleNamespaceContextTests { anyOf(is("prefix1"), is("prefix2"))); } - @Test(expected = IllegalArgumentException.class) + @Test public void getPrefixes_withNull() throws Exception { - context.getPrefixes(null); + assertThatIllegalArgumentException().isThrownBy(() -> + context.getPrefixes(null)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void getPrefixes_IteratorIsNotModifiable() throws Exception { context.bindNamespaceUri(prefix, namespaceUri); Iterator iterator = context.getPrefixes(namespaceUri); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( + iterator::remove); } @Test @@ -120,14 +126,16 @@ public class SimpleNamespaceContextTests { getItemSet(context.getPrefixes(namespaceUri)), is(makeSet("prefix1", "prefix2"))); } - @Test(expected = IllegalArgumentException.class) + @Test public void bindNamespaceUri_withNullNamespaceUri() { - context.bindNamespaceUri("prefix", null); + assertThatIllegalArgumentException().isThrownBy(() -> + context.bindNamespaceUri("prefix", null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void bindNamespaceUri_withNullPrefix() { - context.bindNamespaceUri(null, namespaceUri); + assertThatIllegalArgumentException().isThrownBy(() -> + context.bindNamespaceUri(null, namespaceUri)); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java b/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java index 2157b7be7c7..5364ece36b1 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java @@ -27,6 +27,7 @@ import javax.xml.transform.URIResolver; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -72,19 +73,22 @@ public class TransformerUtilsTests { assertEquals("no", indent); } - @Test(expected = IllegalArgumentException.class) + @Test public void enableIndentingWithNullTransformer() throws Exception { - TransformerUtils.enableIndenting(null); + assertThatIllegalArgumentException().isThrownBy(() -> + TransformerUtils.enableIndenting(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void disableIndentingWithNullTransformer() throws Exception { - TransformerUtils.disableIndenting(null); + assertThatIllegalArgumentException().isThrownBy(() -> + TransformerUtils.disableIndenting(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void enableIndentingWithNegativeIndentAmount() throws Exception { - TransformerUtils.enableIndenting(new StubTransformer(), -21938); + assertThatIllegalArgumentException().isThrownBy(() -> + TransformerUtils.enableIndenting(new StubTransformer(), -21938)); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java index cccf1869809..553efa42d34 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java @@ -19,17 +19,17 @@ package org.springframework.expression.spel; import java.util.Arrays; import java.util.List; -import org.springframework.expression.EvaluationException; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; -import org.springframework.expression.ParseException; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Common superclass for expression tests. @@ -59,9 +59,7 @@ public abstract class AbstractExpressionTests { */ public void evaluate(String expression, Object expectedValue, Class expectedResultType) { Expression expr = parser.parseExpression(expression); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).as("expression").isNotNull(); if (DEBUG) { SpelUtilities.printAbstractSyntaxTree(System.out, expr); } @@ -91,9 +89,7 @@ public abstract class AbstractExpressionTests { public void evaluateAndAskForReturnType(String expression, Object expectedValue, Class expectedResultType) { Expression expr = parser.parseExpression(expression); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).as("expression").isNotNull(); if (DEBUG) { SpelUtilities.printAbstractSyntaxTree(System.out, expr); } @@ -124,9 +120,7 @@ public abstract class AbstractExpressionTests { */ public void evaluate(String expression, Object expectedValue, Class expectedClassOfResult, boolean shouldBeWritable) { Expression expr = parser.parseExpression(expression); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).as("expression").isNotNull(); if (DEBUG) { SpelUtilities.printAbstractSyntaxTree(System.out, expr); } @@ -148,13 +142,7 @@ public abstract class AbstractExpressionTests { assertTrue("Type of the result was not as expected. Expected '" + expectedClassOfResult + "' but result was of type '" + resultType + "'", expectedClassOfResult.equals(resultType)); - boolean isWritable = expr.isWritable(context); - if (isWritable != shouldBeWritable) { - if (shouldBeWritable) - fail("Expected the expression to be writable but it is not"); - else - fail("Expected the expression to be readonly but it is not"); - } + assertThat(expr.isWritable(context)).as("isWritable").isEqualTo(shouldBeWritable); } /** @@ -181,59 +169,31 @@ public abstract class AbstractExpressionTests { */ protected void evaluateAndCheckError(String expression, Class expectedReturnType, SpelMessage expectedMessage, Object... otherProperties) { - try { + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> { Expression expr = parser.parseExpression(expression); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).as("expression").isNotNull(); if (expectedReturnType != null) { expr.getValue(context, expectedReturnType); } else { expr.getValue(context); } - fail("Should have failed with message " + expectedMessage); - } - catch (EvaluationException ee) { - SpelEvaluationException ex = (SpelEvaluationException) ee; - if (ex.getMessageCode() != expectedMessage) { - assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode()); - } - if (otherProperties != null && otherProperties.length != 0) { + }).satisfies(ex -> { + assertThat(ex.getMessageCode()).isEqualTo(expectedMessage); + if (!ObjectUtils.isEmpty(otherProperties)) { // first one is expected position of the error within the string int pos = ((Integer) otherProperties[0]).intValue(); - assertEquals("Did not get correct position reported in error ", pos, ex.getPosition()); + assertThat(ex.getPosition()).as("position").isEqualTo(pos); if (otherProperties.length > 1) { // Check inserts match Object[] inserts = ex.getInserts(); - if (inserts == null) { - inserts = new Object[0]; - } - if (inserts.length < otherProperties.length - 1) { - fail("Cannot check " + (otherProperties.length - 1) + - " properties of the exception, it only has " + inserts.length + " inserts"); - } - for (int i = 1; i < otherProperties.length; i++) { - if (otherProperties[i] == null) { - if (inserts[i - 1] != null) { - fail("Insert does not match, expected 'null' but insert value was '" + - inserts[i - 1] + "'"); - } - } - else if (inserts[i - 1] == null) { - if (otherProperties[i] != null) { - fail("Insert does not match, expected '" + otherProperties[i] + - "' but insert value was 'null'"); - } - } - else if (!inserts[i - 1].equals(otherProperties[i])) { - fail("Insert does not match, expected '" + otherProperties[i] + - "' but insert value was '" + inserts[i - 1] + "'"); - } - } + assertThat(inserts).as("inserts").hasSizeGreaterThanOrEqualTo(otherProperties.length - 1); + Object[] expectedInserts = new Object[inserts.length]; + System.arraycopy(otherProperties, 1, expectedInserts, 0, expectedInserts.length); + assertThat(inserts).as("inserts").containsExactly(expectedInserts); } } - } + }); } /** @@ -245,39 +205,25 @@ public abstract class AbstractExpressionTests { * @param otherProperties the expected inserts within the message */ protected void parseAndCheckError(String expression, SpelMessage expectedMessage, Object... otherProperties) { - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { Expression expr = parser.parseExpression(expression); SpelUtilities.printAbstractSyntaxTree(System.out, expr); - fail("Parsing should have failed!"); - } - catch (ParseException pe) { - SpelParseException ex = (SpelParseException)pe; - if (ex.getMessageCode() != expectedMessage) { - assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode()); - } + }).satisfies(ex -> { + assertThat(ex.getMessageCode()).isEqualTo(expectedMessage); if (otherProperties != null && otherProperties.length != 0) { // first one is expected position of the error within the string int pos = ((Integer) otherProperties[0]).intValue(); - assertEquals("Did not get correct position reported in error ", pos, ex.getPosition()); + assertThat(pos).as("reported position").isEqualTo(pos); if (otherProperties.length > 1) { // Check inserts match Object[] inserts = ex.getInserts(); - if (inserts == null) { - inserts = new Object[0]; - } - if (inserts.length < otherProperties.length - 1) { - fail("Cannot check " + (otherProperties.length - 1) + - " properties of the exception, it only has " + inserts.length + " inserts"); - } - for (int i = 1; i < otherProperties.length; i++) { - if (!inserts[i - 1].equals(otherProperties[i])) { - fail("Insert does not match, expected '" + otherProperties[i] + - "' but insert value was '" + inserts[i - 1] + "'"); - } - } + assertThat(inserts).as("inserts").hasSizeGreaterThanOrEqualTo(otherProperties.length - 1); + Object[] expectedInserts = new Object[inserts.length]; + System.arraycopy(otherProperties, 1, expectedInserts, 0, expectedInserts.length); + assertThat(inserts).as("inserts").containsExactly(expectedInserts); } } - } + }); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java index 506d3058cc9..61080756e42 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java @@ -24,7 +24,6 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test construction of arrays. @@ -199,7 +198,7 @@ public class ArrayConstructorTests extends AbstractExpressionTests { } } else { - fail("Not supported " + o.getClass()); + throw new IllegalStateException("Not supported " + o.getClass()); } s.append(']'); assertEquals(expectedToString, s.toString()); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java index b11e28eb0f5..f94749c22df 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java @@ -32,10 +32,11 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.PlaceOfBirth; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests invocation of constructors. @@ -129,38 +130,25 @@ public class ConstructorInvocationTests extends AbstractExpressionTests { // 4 will make it throw a checked exception - this will be wrapped by spel on the // way out eContext.setVariable("bar", 4); - try { - o = expr.getValue(eContext); - fail("Should have failed"); - } - catch (Exception e) { - // A problem occurred whilst attempting to construct an object of type - // 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' - // using arguments '(java.lang.Integer)' - int idx = e.getMessage().indexOf("Tester"); - if (idx == -1) { - fail("Expected reference to Tester in :" + e.getMessage()); - } - // normal - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + expr.getValue(eContext)) + .withMessageContaining("Tester"); + // A problem occurred whilst attempting to construct an object of type + // 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' + // using arguments '(java.lang.Integer)' + // If counter is 4 then the method got called twice! assertEquals(3, parser.parseExpression("counter").getValue(eContext)); // 1 will make it throw a RuntimeException - SpEL will let this through eContext.setVariable("bar", 1); - try { - o = expr.getValue(eContext); - fail("Should have failed"); - } - catch (Exception e) { - // A problem occurred whilst attempting to construct an object of type - // 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' - // using arguments '(java.lang.Integer)' - if (e instanceof SpelEvaluationException) { - e.printStackTrace(); - fail("Should not have been wrapped"); - } - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + expr.getValue(eContext)) + .satisfies(ex -> assertThat(ex).isNotInstanceOf(SpelEvaluationException.class)); + // A problem occurred whilst attempting to construct an object of type + // 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' + // using arguments '(java.lang.Integer)' + // If counter is 5 then the method got called twice! assertEquals(4, parser.parseExpression("counter").getValue(eContext)); } 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 367f1a8b7c8..80ad495f3b8 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 @@ -42,6 +42,9 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.support.StandardTypeLocator; 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; @@ -49,7 +52,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests the evaluation of real expressions in a real context. @@ -75,21 +77,15 @@ public class EvaluationTests extends AbstractExpressionTests { assertEquals("", o); assertEquals(4, testClass.list.size()); - try { - o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass)); - fail(); - } - catch (EvaluationException ee) { - ee.printStackTrace(); - // success! - } + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass))); o = parser.parseExpression("foo[3]").getValue(new StandardEvaluationContext(testClass)); assertEquals("", o); assertEquals(4, testClass.getFoo().size()); } - @Test(expected = SpelEvaluationException.class) + @Test public void testCreateMapsOnAttemptToIndexNull01() { TestClass testClass = new TestClass(); StandardEvaluationContext ctx = new StandardEvaluationContext(testClass); @@ -100,12 +96,13 @@ public class EvaluationTests extends AbstractExpressionTests { o = parser.parseExpression("map").getValue(ctx); assertNotNull(o); - o = parser.parseExpression("map2['a']").getValue(ctx); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + parser.parseExpression("map2['a']").getValue(ctx)); // map2 should be null, there is no setter } // wibble2 should be null (cannot be initialized dynamically), there is no setter - @Test(expected = SpelEvaluationException.class) + @Test public void testCreateObjectsOnAttemptToReferenceNull() { TestClass testClass = new TestClass(); StandardEvaluationContext ctx = new StandardEvaluationContext(testClass); @@ -116,7 +113,8 @@ public class EvaluationTests extends AbstractExpressionTests { o = parser.parseExpression("wibble").getValue(ctx); assertNotNull(o); - o = parser.parseExpression("wibble2.bar").getValue(ctx); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + parser.parseExpression("wibble2.bar").getValue(ctx)); } @Test @@ -205,15 +203,10 @@ public class EvaluationTests extends AbstractExpressionTests { String pattern = "^(?=[a-z0-9-]{1,47})([a-z0-9]+[-]{0,1}){1,47}[a-z0-9]{1}$"; String expression = "'abcde-fghijklmn-o42pasdfasdfasdf.qrstuvwxyz10x.xx.yyy.zasdfasfd' matches \'" + pattern + "\'"; Expression expr = parser.parseExpression(expression); - try { - expr.getValue(); - fail("Should have exceeded threshold"); - } - catch (EvaluationException ee) { - SpelEvaluationException see = (SpelEvaluationException) ee; - assertEquals(SpelMessage.FLAWED_PATTERN, see.getMessageCode()); - assertTrue(see.getCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( + expr::getValue) + .withCauseInstanceOf(IllegalStateException.class) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.FLAWED_PATTERN)); } // mixing operators @@ -239,14 +232,12 @@ public class EvaluationTests extends AbstractExpressionTests { @Test public void testRogueTrailingDotCausesNPE_SPR6866() { - try { - new SpelExpressionParser().parseExpression("placeOfBirth.foo."); - fail("Should have failed to parse"); - } - catch (SpelParseException ex) { - assertEquals(SpelMessage.OOD, ex.getMessageCode()); - assertEquals(16, ex.getPosition()); - } + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> + new SpelExpressionParser().parseExpression("placeOfBirth.foo.")) + .satisfies(ex -> { + assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OOD); + assertThat(ex.getPosition()).isEqualTo(16); + }); } // nested properties @@ -262,14 +253,12 @@ public class EvaluationTests extends AbstractExpressionTests { @Test public void testPropertiesNested03() throws ParseException { - try { - new SpelExpressionParser().parseRaw("placeOfBirth.23"); - fail(); - } - catch (SpelParseException spe) { - assertEquals(SpelMessage.UNEXPECTED_DATA_AFTER_DOT, spe.getMessageCode()); - assertEquals("23", spe.getInserts()[0]); - } + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> + new SpelExpressionParser().parseRaw("placeOfBirth.23")) + .satisfies(ex -> { + assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.UNEXPECTED_DATA_AFTER_DOT); + assertThat(ex.getInserts()[0]).isEqualTo("23"); + }); } // methods @@ -331,29 +320,34 @@ public class EvaluationTests extends AbstractExpressionTests { evaluate("!false", "true", Boolean.class); } - @Test(expected = EvaluationException.class) + @Test public void testUnaryNotWithNullValue() { - parser.parseExpression("!null").getValue(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + parser.parseExpression("!null")::getValue); } - @Test(expected = EvaluationException.class) + @Test public void testAndWithNullValueOnLeft() { - parser.parseExpression("null and true").getValue(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + parser.parseExpression("null and true")::getValue); } - @Test(expected = EvaluationException.class) + @Test public void testAndWithNullValueOnRight() { - parser.parseExpression("true and null").getValue(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + parser.parseExpression("true and null")::getValue); } - @Test(expected = EvaluationException.class) + @Test public void testOrWithNullValueOnLeft() { - parser.parseExpression("null or false").getValue(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + parser.parseExpression("null or false")::getValue); } - @Test(expected = EvaluationException.class) + @Test public void testOrWithNullValueOnRight() { - parser.parseExpression("false or null").getValue(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + parser.parseExpression("false or null")::getValue); } // assignment @@ -392,9 +386,10 @@ public class EvaluationTests extends AbstractExpressionTests { evaluate("2>4?(3>2?true:false):(5<3?true:false)", false, Boolean.class); } - @Test(expected = EvaluationException.class) + @Test public void testTernaryOperatorWithNullValue() { - parser.parseExpression("null ? 0 : 1").getValue(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + parser.parseExpression("null ? 0 : 1")::getValue); } @Test @@ -552,13 +547,8 @@ public class EvaluationTests extends AbstractExpressionTests { @Test public void testResolvingList() { StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); - try { - assertFalse(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)); - fail("should have failed to find List"); - } - catch (EvaluationException ee) { - // success - List not found - } + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)); ((StandardTypeLocator) context.getTypeLocator()).registerImport("java.util"); assertTrue(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)); } @@ -631,15 +621,9 @@ public class EvaluationTests extends AbstractExpressionTests { // Register a custom MethodFilter... MethodFilter filter = new CustomMethodFilter(); - try { - context.registerMethodFilter(String.class, filter); - fail("should have failed"); - } - catch (IllegalStateException ise) { - assertEquals( - "Method filter cannot be set as the reflective method resolver is not in use", - ise.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + context.registerMethodFilter(String.class, filter)) + .withMessage("Method filter cannot be set as the reflective method resolver is not in use"); } /** @@ -672,16 +656,12 @@ public class EvaluationTests extends AbstractExpressionTests { assertEquals("",value); // Now turn off growing and reference off the end - ctx = new StandardEvaluationContext(instance); + StandardEvaluationContext failCtx = new StandardEvaluationContext(instance); parser = new SpelExpressionParser(new SpelParserConfiguration(false, false)); - e = parser.parseExpression("listOfStrings[3]"); - try { - e.getValue(ctx, String.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, see.getMessageCode()); - } + Expression failExp = parser.parseExpression("listOfStrings[3]"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + failExp.getValue(failCtx, String.class)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS)); } @Test @@ -710,13 +690,9 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e = parser.parseExpression("#this++"); assertEquals(42,i.intValue()); - try { - e.getValue(ctx, Integer.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e.getValue(ctx, Integer.class)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); } @Test @@ -831,25 +807,16 @@ public class EvaluationTests extends AbstractExpressionTests { Spr9751 helper = new Spr9751(); StandardEvaluationContext ctx = new StandardEvaluationContext(helper); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); - Expression e; - e = parser.parseExpression("m()++"); - try { - e.getValue(ctx, Double.TYPE); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE, see.getMessageCode()); - } + Expression e1 = parser.parseExpression("m()++"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e1.getValue(ctx, Double.TYPE)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_INCREMENTABLE)); - e = parser.parseExpression("++m()"); - try { - e.getValue(ctx, Double.TYPE); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE, see.getMessageCode()); - } + Expression e2 = parser.parseExpression("++m()"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e2.getValue(ctx, Double.TYPE)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_INCREMENTABLE)); } @Test @@ -857,22 +824,14 @@ public class EvaluationTests extends AbstractExpressionTests { Integer i = 42; StandardEvaluationContext ctx = new StandardEvaluationContext(i); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); - try { - Expression e = parser.parseExpression("++1"); - e.getValue(ctx, Integer.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); - } - try { - Expression e = parser.parseExpression("1++"); - e.getValue(ctx, Integer.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); - } + Expression e1 = parser.parseExpression("++1"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e1.getValue(ctx, Double.TYPE)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); + Expression e2 = parser.parseExpression("1++"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e2.getValue(ctx, Double.TYPE)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); } @Test @@ -882,13 +841,9 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e = parser.parseExpression("#this--"); assertEquals(42, i.intValue()); - try { - e.getValue(ctx, Integer.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e.getValue(ctx, Integer.class)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); } @Test @@ -1002,25 +957,16 @@ public class EvaluationTests extends AbstractExpressionTests { Spr9751 helper = new Spr9751(); StandardEvaluationContext ctx = new StandardEvaluationContext(helper); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); - Expression e; - e = parser.parseExpression("m()--"); - try { - e.getValue(ctx, Double.TYPE); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE, see.getMessageCode()); - } + Expression e1 = parser.parseExpression("m()--"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e1.getValue(ctx, Double.TYPE)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_DECREMENTABLE)); - e = parser.parseExpression("--m()"); - try { - e.getValue(ctx, Double.TYPE); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE, see.getMessageCode()); - } + Expression e2 = parser.parseExpression("--m()"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e2.getValue(ctx, Double.TYPE)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_DECREMENTABLE)); } @@ -1029,22 +975,15 @@ public class EvaluationTests extends AbstractExpressionTests { Integer i = 42; StandardEvaluationContext ctx = new StandardEvaluationContext(i); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); - try { - Expression e = parser.parseExpression("--1"); - e.getValue(ctx, Integer.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); - } - try { - Expression e = parser.parseExpression("1--"); - e.getValue(ctx, Integer.class); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); - } + Expression e1 = parser.parseExpression("--1"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e1.getValue(ctx, Integer.class)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); + + Expression e2 = parser.parseExpression("1--"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e2.getValue(ctx, Integer.class)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); } @Test @@ -1380,19 +1319,6 @@ public class EvaluationTests extends AbstractExpressionTests { assertEquals(100, helper.iii); } - - private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) { - try { - Expression e = parser.parseExpression(expressionString); - SpelUtilities.printAbstractSyntaxTree(System.out, e); - e.getValue(eContext); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(messageCode, see.getMessageCode()); - } - } - private void expectFailNotAssignable(ExpressionParser parser, EvaluationContext eContext, String expressionString) { expectFail(parser, eContext, expressionString, SpelMessage.NOT_ASSIGNABLE); } @@ -1409,6 +1335,13 @@ public class EvaluationTests extends AbstractExpressionTests { expectFail(parser, eContext, expressionString, SpelMessage.OPERAND_NOT_DECREMENTABLE); } + private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) { + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> { + Expression e = parser.parseExpression(expressionString); + SpelUtilities.printAbstractSyntaxTree(System.out, e); + e.getValue(eContext); + }).satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(messageCode)); + } static class CustomMethodResolver implements MethodResolver { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java index d2db50e8d7d..fd0df8814c5 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java @@ -35,8 +35,9 @@ import org.springframework.expression.TypedValue; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; ///CLOVER:OFF @@ -82,8 +83,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { assertEquals(String.class, value.getClass()); } catch (EvaluationException | ParseException ex) { - ex.printStackTrace(); - fail("Unexpected Exception: " + ex.getMessage()); + throw new AssertionError(ex.getMessage(), ex); } } @@ -187,8 +187,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { } catch (EvaluationException | ParseException ex) { - ex.printStackTrace(); - fail("Unexpected Exception: " + ex.getMessage()); + throw new AssertionError(ex.getMessage(), ex); } } @@ -206,14 +205,9 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { Expression expr = parser.parseRaw("orange"); Object value = expr.getValue(ctx); assertEquals(Color.orange, value); - - try { - expr.setValue(ctx, Color.blue); - fail("Should not be allowed to set oranges to be blue !"); - } - catch (SpelEvaluationException ee) { - assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expr.setValue(ctx, Color.blue)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL)); } @Test @@ -228,13 +222,9 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { Object value = expr.getValue(ctx); assertEquals(Color.green, value); - try { - expr.setValue(ctx, Color.blue); - fail("Should not be allowed to set peas to be blue !"); - } - catch (SpelEvaluationException ee) { - assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expr.setValue(ctx, Color.blue)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL)); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java index a2af997df86..dbaf3bc82a8 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java @@ -29,10 +29,12 @@ import org.springframework.expression.TypedValue; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.Inventor; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * Tests for the expression state object - some features are not yet exploited in the language (eg nested scopes) @@ -140,13 +142,8 @@ public class ExpressionStateTests extends AbstractExpressionTests { ExpressionState state = getState(); assertEquals(state.getRootContextObject().getValue(), state.getActiveContextObject().getValue()); - try { - state.popActiveContextObject(); - fail("stack should be empty..."); - } - catch (IllegalStateException ese) { - // success - } + assertThatIllegalStateException().isThrownBy( + state::popActiveContextObject); state.pushActiveContextObject(new TypedValue(34)); assertEquals(34, state.getActiveContextObject().getValue()); @@ -222,23 +219,13 @@ public class ExpressionStateTests extends AbstractExpressionTests { @Test public void testOperators() { ExpressionState state = getState(); - try { - state.operate(Operation.ADD,1,2); - fail("should have failed"); - } - catch (EvaluationException ee) { - SpelEvaluationException sEx = (SpelEvaluationException)ee; - assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES, sEx.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + state.operate(Operation.ADD,1,2)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES)); - try { - state.operate(Operation.ADD,null,null); - fail("should have failed"); - } - catch (EvaluationException ee) { - SpelEvaluationException sEx = (SpelEvaluationException)ee; - assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES, sEx.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + state.operate(Operation.ADD,null,null)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES)); } @Test @@ -252,14 +239,10 @@ public class ExpressionStateTests extends AbstractExpressionTests { ExpressionState state = getState(); assertNotNull(state.getEvaluationContext().getTypeLocator()); assertEquals(Integer.class, state.findType("java.lang.Integer")); - try { - state.findType("someMadeUpName"); - fail("Should have failed to find it"); - } - catch (EvaluationException ee) { - SpelEvaluationException sEx = (SpelEvaluationException)ee; - assertEquals(SpelMessage.TYPE_NOT_FOUND, sEx.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + state.findType("someMadeUpName")) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_NOT_FOUND)); + } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java index af8132cd95e..0969b8fa16d 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java @@ -25,6 +25,7 @@ import org.springframework.expression.spel.ast.InlineList; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -156,9 +157,10 @@ public class ListTests extends AbstractExpressionTests { } } - @Test(expected = UnsupportedOperationException.class) + @Test public void testInlineListWriting() { // list should be unmodifiable - evaluate("{1, 2, 3, 4, 5}[0]=6", "[1, 2, 3, 4, 5]", unmodifiableClass); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + evaluate("{1, 2, 3, 4, 5}[0]=6", "[1, 2, 3, 4, 5]", unmodifiableClass)); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java index f16c8d533fa..9e127204eb3 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java @@ -23,9 +23,10 @@ import org.springframework.expression.EvaluationException; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; /** * @author Andy Clement @@ -35,15 +36,15 @@ public class LiteralExpressionTests { @Test public void testGetValue() throws Exception { LiteralExpression lEx = new LiteralExpression("somevalue"); - checkString("somevalue", lEx.getValue()); - checkString("somevalue", lEx.getValue(String.class)); + assertThat(lEx.getValue()).isInstanceOf(String.class).isEqualTo("somevalue"); + assertThat(lEx.getValue(String.class)).isInstanceOf(String.class).isEqualTo("somevalue"); EvaluationContext ctx = new StandardEvaluationContext(); - checkString("somevalue", lEx.getValue(ctx)); - checkString("somevalue", lEx.getValue(ctx, String.class)); - checkString("somevalue", lEx.getValue(new Rooty())); - checkString("somevalue", lEx.getValue(new Rooty(), String.class)); - checkString("somevalue", lEx.getValue(ctx, new Rooty())); - checkString("somevalue", lEx.getValue(ctx, new Rooty(),String.class)); + assertThat(lEx.getValue(ctx)).isInstanceOf(String.class).isEqualTo("somevalue"); + assertThat(lEx.getValue(ctx, String.class)).isInstanceOf(String.class).isEqualTo("somevalue"); + assertThat(lEx.getValue(new Rooty())).isInstanceOf(String.class).isEqualTo("somevalue"); + assertThat(lEx.getValue(new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("somevalue"); + assertThat(lEx.getValue(ctx, new Rooty())).isInstanceOf(String.class).isEqualTo("somevalue"); + assertThat(lEx.getValue(ctx, new Rooty(),String.class)).isInstanceOf(String.class).isEqualTo("somevalue"); assertEquals("somevalue", lEx.getExpressionString()); assertFalse(lEx.isWritable(new StandardEvaluationContext())); assertFalse(lEx.isWritable(new Rooty())); @@ -54,33 +55,15 @@ public class LiteralExpressionTests { @Test public void testSetValue() { - try { - LiteralExpression lEx = new LiteralExpression("somevalue"); - lEx.setValue(new StandardEvaluationContext(), "flibble"); - fail("Should have got an exception that the value cannot be set"); - } - catch (EvaluationException ee) { - // success, not allowed - whilst here, check the expression value in the exception - assertEquals("somevalue", ee.getExpressionString()); - } - try { - LiteralExpression lEx = new LiteralExpression("somevalue"); - lEx.setValue(new Rooty(), "flibble"); - fail("Should have got an exception that the value cannot be set"); - } - catch (EvaluationException ee) { - // success, not allowed - whilst here, check the expression value in the exception - assertEquals("somevalue", ee.getExpressionString()); - } - try { - LiteralExpression lEx = new LiteralExpression("somevalue"); - lEx.setValue(new StandardEvaluationContext(), new Rooty(), "flibble"); - fail("Should have got an exception that the value cannot be set"); - } - catch (EvaluationException ee) { - // success, not allowed - whilst here, check the expression value in the exception - assertEquals("somevalue", ee.getExpressionString()); - } + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + new LiteralExpression("somevalue").setValue(new StandardEvaluationContext(), "flibble")) + .satisfies(ex -> assertThat(ex.getExpressionString()).isEqualTo("somevalue")); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + new LiteralExpression("somevalue").setValue(new Rooty(), "flibble")) + .satisfies(ex -> assertThat(ex.getExpressionString()).isEqualTo("somevalue")); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + new LiteralExpression("somevalue").setValue(new StandardEvaluationContext(), new Rooty(), "flibble")) + .satisfies(ex -> assertThat(ex.getExpressionString()).isEqualTo("somevalue")); } @Test @@ -96,13 +79,4 @@ public class LiteralExpressionTests { assertEquals(String.class, lEx.getValueTypeDescriptor(new StandardEvaluationContext(), new Rooty()).getType()); } - private void checkString(String expectedString, Object value) { - if (!(value instanceof String)) { - fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")"); - } - if (!((String) value).equals(expectedString)) { - fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'"); - } - } - } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java index 842db9cc1b5..5cf3292433a 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java @@ -28,6 +28,7 @@ import org.springframework.expression.spel.ast.InlineMap; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -134,10 +135,11 @@ public class MapTests extends AbstractExpressionTests { } } - @Test(expected = UnsupportedOperationException.class) + @Test public void testInlineMapWriting() { // list should be unmodifiable - evaluate("{a:1, b:2, c:3, d:4, e:5}[a]=6", "[a:1,b: 2,c: 3,d: 4,e: 5]", unmodifiableClass); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + evaluate("{a:1, b:2, c:3, d:4, e:5}[a]=6", "[a:1,b: 2,c: 3,d: 4,e: 5]", unmodifiableClass)); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java index e8ea8237381..9c7e25d33ac 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java @@ -39,11 +39,12 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.PlaceOfBirth; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests invocation of methods. @@ -124,31 +125,17 @@ public class MethodInvocationTests extends AbstractExpressionTests { // Now cause it to throw an exception: eContext.setVariable("bar", 1); - try { - o = expr.getValue(eContext); - fail(); - } - catch (Exception ex) { - if (ex instanceof SpelEvaluationException) { - fail("Should not be a SpelEvaluationException: " + ex); - } - // normal - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + expr.getValue(eContext)) + .isNotInstanceOf(SpelEvaluationException.class); + // If counter is 4 then the method got called twice! assertEquals(3, parser.parseExpression("counter").getValue(eContext)); eContext.setVariable("bar", 4); - try { - o = expr.getValue(eContext); - fail(); - } - catch (Exception ex) { - // 4 means it will throw a checked exception - this will be wrapped - if (!(ex instanceof ExpressionInvocationTargetException)) { - fail("Should have been wrapped: " + ex); - } - // normal - } + assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() -> + expr.getValue(eContext)); + // If counter is 5 then the method got called twice! assertEquals(4, parser.parseExpression("counter").getValue(eContext)); } @@ -168,16 +155,9 @@ public class MethodInvocationTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("throwException(#bar)"); context.setVariable("bar", 2); - try { - expr.getValue(context); - fail(); - } - catch (Exception ex) { - if (ex instanceof SpelEvaluationException) { - fail("Should not be a SpelEvaluationException: " + ex); - } - // normal - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + expr.getValue(context)) + .satisfies(ex -> assertThat(ex).isNotInstanceOf(SpelEvaluationException.class)); } @Test @@ -192,15 +172,10 @@ public class MethodInvocationTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("throwException(#bar)"); context.setVariable("bar", 4); - try { - expr.getValue(context); - fail(); - } - catch (ExpressionInvocationTargetException ex) { - Throwable cause = ex.getCause(); - assertEquals("org.springframework.expression.spel.testresources.Inventor$TestException", - cause.getClass().getName()); - } + assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() -> + expr.getValue(context)) + .satisfies(ex -> assertThat(ex.getCause().getClass().getName()).isEqualTo( + "org.springframework.expression.spel.testresources.Inventor$TestException")); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ParsingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ParsingTests.java index 44c938a8593..181f5d88428 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ParsingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ParsingTests.java @@ -18,12 +18,10 @@ package org.springframework.expression.spel; import org.junit.Test; -import org.springframework.expression.ParseException; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; /** * Parse some expressions and check we get the AST we expect. Rather than inspecting each node in the AST, we ask it to @@ -454,20 +452,9 @@ public class ParsingTests { * @param expectedStringFormOfAST the expected string form of the AST */ public void parseCheck(String expression, String expectedStringFormOfAST) { - try { - SpelExpression e = parser.parseRaw(expression); - if (e != null && !e.toStringAST().equals(expectedStringFormOfAST)) { - SpelUtilities.printAbstractSyntaxTree(System.err, e); - } - if (e == null) { - fail("Parsed exception was null"); - } - assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST()); - } - catch (ParseException ee) { - ee.printStackTrace(); - fail("Unexpected Exception: " + ee.getMessage()); - } + SpelExpression e = parser.parseRaw(expression); + assertThat(e).isNotNull(); + assertThat(e.toStringAST()).isEqualTo(expectedStringFormOfAST); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java index 7e64b0123d8..8ab29bfd765 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java @@ -25,6 +25,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; ///CLOVER:OFF @@ -54,18 +55,14 @@ public class PerformanceTests { // warmup for (int i = 0; i < ITERATIONS; i++) { Expression expr = parser.parseExpression("placeOfBirth.city"); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).isNotNull(); expr.getValue(eContext); } starttime = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { Expression expr = parser.parseExpression("placeOfBirth.city"); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).isNotNull(); expr.getValue(eContext); } endtime = System.currentTimeMillis(); @@ -75,9 +72,7 @@ public class PerformanceTests { } Expression expr = parser.parseExpression("placeOfBirth.city"); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).isNotNull(); starttime = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { expr.getValue(eContext); @@ -104,18 +99,14 @@ public class PerformanceTests { // warmup for (int i = 0; i < ITERATIONS; i++) { Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()"); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).isNotNull(); expr.getValue(eContext); } starttime = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()"); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).isNotNull(); expr.getValue(eContext); } endtime = System.currentTimeMillis(); @@ -125,9 +116,7 @@ public class PerformanceTests { } Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()"); - if (expr == null) { - fail("Parser returned null for expression"); - } + assertThat(expr).isNotNull(); starttime = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { expr.getValue(eContext); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java index e0f940bf2c9..3f1418940c5 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java @@ -36,12 +36,13 @@ import org.springframework.expression.spel.support.SimpleEvaluationContext; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.Person; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests accessing of properties. @@ -83,31 +84,13 @@ public class PropertyAccessTests extends AbstractExpressionTests { public void testAccessingOnNullObject() { SpelExpression expr = (SpelExpression)parser.parseExpression("madeup"); EvaluationContext context = new StandardEvaluationContext(null); - try { - expr.getValue(context); - fail("Should have failed - default property resolver cannot resolve on null"); - } - catch (Exception ex) { - checkException(ex, SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expr.getValue(context)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL)); assertFalse(expr.isWritable(context)); - try { - expr.setValue(context, "abc"); - fail("Should have failed - default property resolver cannot resolve on null"); - } - catch (Exception ex) { - checkException(ex, SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL); - } - } - - private void checkException(Exception ex, SpelMessage expectedMessage) { - if (ex instanceof SpelEvaluationException) { - SpelMessage sm = ((SpelEvaluationException) ex).getMessageCode(); - assertEquals("Expected exception type did not occur", expectedMessage, sm); - } - else { - fail("Should be a SpelException " + ex); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expr.setValue(context, "abc")) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL)); } @Test @@ -129,21 +112,17 @@ public class PropertyAccessTests extends AbstractExpressionTests { Object o = expr.getValue(ctx); assertNotNull(o); - expr = parser.parseRaw("new String('hello').flibbles"); - expr.setValue(ctx, 99); - i = expr.getValue(ctx, Integer.class); + SpelExpression flibbleexpr = parser.parseRaw("new String('hello').flibbles"); + flibbleexpr.setValue(ctx, 99); + i = flibbleexpr.getValue(ctx, Integer.class); assertEquals(99, (int) i); // Cannot set it to a string value - try { - expr.setValue(ctx, "not allowed"); - fail("Should not have been allowed"); - } - catch (EvaluationException ex) { - // success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property - // 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String'' - // System.out.println(e.getMessage()); - } + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + flibbleexpr.setValue(ctx, "not allowed")); + // message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property + // 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String'' + // System.out.println(e.getMessage()); } @Test @@ -194,11 +173,11 @@ public class PropertyAccessTests extends AbstractExpressionTests { assertEquals(String.class.getName(), parser.parseExpression("'a'.class.name").getValue()); } - @Test(expected = SpelEvaluationException.class) + @Test public void noGetClassAccess() { EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build(); - - parser.parseExpression("'a'.class.name").getValue(context); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + parser.parseExpression("'a'.class.name").getValue(context)); } @Test @@ -211,13 +190,8 @@ public class PropertyAccessTests extends AbstractExpressionTests { target.setName("p2"); assertEquals("p2", expr.getValue(context, target)); - try { - parser.parseExpression("name='p3'").getValue(context, target); - fail("Should have thrown SpelEvaluationException"); - } - catch (SpelEvaluationException ex) { - // expected - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + parser.parseExpression("name='p3'").getValue(context, target)); } @Test @@ -263,13 +237,8 @@ public class PropertyAccessTests extends AbstractExpressionTests { public void propertyAccessWithoutMethodResolver() { EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build(); Person target = new Person("p1"); - try { - parser.parseExpression("name.substring(1)").getValue(context, target); - fail("Should have thrown SpelEvaluationException"); - } - catch (SpelEvaluationException ex) { - // expected - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + parser.parseExpression("name.substring(1)").getValue(context, target)); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java b/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java index f6b7a00910c..66adb1fc15f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java @@ -25,7 +25,6 @@ import org.springframework.core.MethodParameter; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; import org.springframework.expression.EvaluationContext; -import org.springframework.expression.EvaluationException; import org.springframework.expression.Expression; import org.springframework.expression.MethodExecutor; import org.springframework.expression.MethodResolver; @@ -38,7 +37,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; ///CLOVER:OFF /** @@ -50,24 +48,17 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests { @Test public void testScenario01_Roles() throws Exception { - try { - SpelExpressionParser parser = new SpelExpressionParser(); - StandardEvaluationContext ctx = new StandardEvaluationContext(); - Expression expr = parser.parseRaw("hasAnyRole('MANAGER','TELLER')"); + SpelExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext ctx = new StandardEvaluationContext(); + Expression expr = parser.parseRaw("hasAnyRole('MANAGER','TELLER')"); - ctx.setRootObject(new Person("Ben")); - Boolean value = expr.getValue(ctx,Boolean.class); - assertFalse(value); + ctx.setRootObject(new Person("Ben")); + Boolean value = expr.getValue(ctx,Boolean.class); + assertFalse(value); - ctx.setRootObject(new Manager("Luke")); - value = expr.getValue(ctx,Boolean.class); - assertTrue(value); - - } - catch (EvaluationException ee) { - ee.printStackTrace(); - fail("Unexpected SpelException: " + ee.getMessage()); - } + ctx.setRootObject(new Manager("Luke")); + value = expr.getValue(ctx,Boolean.class); + assertTrue(value); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java index c3019cb9f7b..9778ff4c811 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java @@ -27,11 +27,12 @@ import org.springframework.expression.ParseException; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.PlaceOfBirth; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests set value expressions. @@ -84,53 +85,37 @@ public class SetValueTests extends AbstractExpressionTests { @Test public void testIsWritableForInvalidExpressions_SPR10610() { - Expression e = null; StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext(); // PROPERTYORFIELDREFERENCE // Non existent field (or property): - e = parser.parseExpression("arrayContainer.wibble"); - assertFalse("Should not be writable!",e.isWritable(lContext)); + Expression e1 = parser.parseExpression("arrayContainer.wibble"); + assertFalse("Should not be writable!", e1.isWritable(lContext)); - e = parser.parseExpression("arrayContainer.wibble.foo"); - try { - assertFalse("Should not be writable!",e.isWritable(lContext)); - fail("Should have had an error because wibble does not really exist"); - } - catch (SpelEvaluationException see) { + Expression e2 = parser.parseExpression("arrayContainer.wibble.foo"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e2.isWritable(lContext)); // org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 15): Property or field 'wibble' cannot be found on object of type 'org.springframework.expression.spel.testresources.ArrayContainer' - maybe not public? // at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:225) - // success! - } // VARIABLE // the variable does not exist (but that is OK, we should be writable) - e = parser.parseExpression("#madeup1"); - assertTrue("Should be writable!",e.isWritable(lContext)); + Expression e3 = parser.parseExpression("#madeup1"); + assertTrue("Should be writable!",e3.isWritable(lContext)); - e = parser.parseExpression("#madeup2.bar"); // compound expression - assertFalse("Should not be writable!",e.isWritable(lContext)); + Expression e4 = parser.parseExpression("#madeup2.bar"); // compound expression + assertFalse("Should not be writable!",e4.isWritable(lContext)); // INDEXER // non existent indexer (wibble made up) - e = parser.parseExpression("arrayContainer.wibble[99]"); - try { - assertFalse("Should not be writable!",e.isWritable(lContext)); - fail("Should have had an error because wibble does not really exist"); - } - catch (SpelEvaluationException see) { - // success! - } + Expression e5 = parser.parseExpression("arrayContainer.wibble[99]"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e5.isWritable(lContext)); // non existent indexer (index via a string) - e = parser.parseExpression("arrayContainer.ints['abc']"); - try { - assertFalse("Should not be writable!",e.isWritable(lContext)); - fail("Should have had an error because wibble does not really exist"); - } - catch (SpelEvaluationException see) { - // success! - } + Expression e6 = parser.parseExpression("arrayContainer.ints['abc']"); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + e6.isWritable(lContext)); } @Test @@ -245,33 +230,20 @@ public class SetValueTests extends AbstractExpressionTests { * Call setValue() but expect it to fail. */ protected void setValueExpectError(String expression, Object value) { - try { - Expression e = parser.parseExpression(expression); - if (e == null) { - fail("Parser returned null for expression"); - } - if (DEBUG) { - SpelUtilities.printAbstractSyntaxTree(System.out, e); - } - StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext(); - e.setValue(lContext, value); - fail("expected an error"); - } - catch (ParseException pe) { - pe.printStackTrace(); - fail("Unexpected Exception: " + pe.getMessage()); - } - catch (EvaluationException ee) { - // success! + Expression e = parser.parseExpression(expression); + assertThat(e).isNotNull(); + if (DEBUG) { + SpelUtilities.printAbstractSyntaxTree(System.out, e); } + StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext(); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + e.setValue(lContext, value)); } protected void setValue(String expression, Object value) { try { Expression e = parser.parseExpression(expression); - if (e == null) { - fail("Parser returned null for expression"); - } + assertThat(e).isNotNull(); if (DEBUG) { SpelUtilities.printAbstractSyntaxTree(System.out, e); } @@ -281,8 +253,7 @@ public class SetValueTests extends AbstractExpressionTests { assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass())); } catch (EvaluationException | ParseException ex) { - ex.printStackTrace(); - fail("Unexpected Exception: " + ex.getMessage()); + throw new AssertionError("Unexpected Exception: " + ex.getMessage(), ex); } } @@ -293,9 +264,7 @@ public class SetValueTests extends AbstractExpressionTests { protected void setValue(String expression, Object value, Object expectedValue) { try { Expression e = parser.parseExpression(expression); - if (e == null) { - fail("Parser returned null for expression"); - } + assertThat(e).isNotNull(); if (DEBUG) { SpelUtilities.printAbstractSyntaxTree(System.out, e); } @@ -304,14 +273,10 @@ public class SetValueTests extends AbstractExpressionTests { e.setValue(lContext, value); Object a = expectedValue; Object b = e.getValue(lContext); - if (!a.equals(b)) { - fail("Not the same: ["+a+"] type="+a.getClass()+" ["+b+"] type="+b.getClass()); -// assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext)); - } + assertThat(a).isEqualTo(b); } catch (EvaluationException | ParseException ex) { - ex.printStackTrace(); - fail("Unexpected Exception: " + ex.getMessage()); + throw new AssertionError("Unexpected Exception: " + ex.getMessage(), ex); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java index dd921a3defe..bc01e6ee37f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java @@ -45,12 +45,12 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testdata.PersonInOtherPackage; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Checks SpelCompiler behavior. This should cover compilation all compiled node types. @@ -1251,13 +1251,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.setVariable("target", "123"); assertEquals("123", expression.getValue(ctx)); ctx.setVariable("target", 42); - try { - assertEquals(42, expression.getValue(ctx)); - fail(); - } - catch (SpelEvaluationException see) { - assertTrue(see.getCause() instanceof ClassCastException); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expression.getValue(ctx)) + .withCauseInstanceOf(ClassCastException.class); ctx.setVariable("target", "abc"); expression = parser.parseExpression("#target.charAt(0)"); @@ -1267,13 +1263,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.setVariable("target", "1"); assertEquals('1', expression.getValue(ctx)); ctx.setVariable("target", 42); - try { - assertEquals('4', expression.getValue(ctx)); - fail(); - } - catch (SpelEvaluationException see) { - assertTrue(see.getCause() instanceof ClassCastException); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expression.getValue(ctx)) + .withCauseInstanceOf(ClassCastException.class); } @Test @@ -4004,14 +3996,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertEquals(2, expression.getValue(is)); assertCanCompile(expression); assertEquals(2, expression.getValue(is)); - - try { - assertEquals(2, expression.getValue(strings)); - fail(); - } - catch (SpelEvaluationException see) { - assertTrue(see.getCause() instanceof ClassCastException); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expression.getValue(strings)) + .withCauseInstanceOf(ClassCastException.class); SpelCompiler.revertToInterpreted(expression); assertEquals("b", expression.getValue(strings)); assertCanCompile(expression); @@ -4037,26 +4024,18 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); tc.obj=new Integer(42); - try { - expression.getValue(tc); - fail(); - } - catch (SpelEvaluationException see) { - assertTrue(see.getCause() instanceof ClassCastException); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expression.getValue(tc)) + .withCauseInstanceOf(ClassCastException.class); + // method with changing target expression = parser.parseExpression("#root.charAt(0)"); assertEquals('a', expression.getValue("abc")); assertCanCompile(expression); - try { - expression.getValue(new Integer(42)); - fail(); - } - catch (SpelEvaluationException see) { - // java.lang.Integer cannot be cast to java.lang.String - assertTrue(see.getCause() instanceof ClassCastException); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + expression.getValue(new Integer(42))) + .withCauseInstanceOf(ClassCastException.class); } @Test @@ -5179,13 +5158,8 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { } private void assertGetValueFail(Expression expression) { - try { - Object o = expression.getValue(); - fail("Calling getValue on the expression should have failed but returned "+o); - } - catch (Exception ex) { - // success! - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + expression.getValue()); } private void assertIsCompiled(Expression expression) { @@ -5196,7 +5170,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertNotNull(object); } catch (Exception ex) { - fail(ex.toString()); + throw new AssertionError(ex.getMessage(), ex); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java index c2fa987f6c1..af745963526 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java @@ -373,7 +373,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { assertEquals(interpretedResult,compiledResult); reportPerformance("method reference", interpretedTotal, compiledTotal); - if (compiledTotal>=interpretedTotal) { + if (compiledTotal >= interpretedTotal) { fail("Compiled version is slower than interpreted!"); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java index bac39e1c453..3bb71af8511 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java @@ -26,6 +26,7 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertTrue; /** @@ -36,18 +37,20 @@ import static org.junit.Assert.assertTrue; */ public class SpelExceptionTests { - @Test(expected = SpelEvaluationException.class) + @Test public void spelExpressionMapNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aMap.containsKey('one')"); - spelExpression.getValue(); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( + spelExpression::getValue); } - @Test(expected = SpelEvaluationException.class) + @Test public void spelExpressionMapIndexAccessNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1"); - spelExpression.getValue(); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( + spelExpression::getValue); } @Test @@ -73,18 +76,20 @@ public class SpelExceptionTests { } - @Test(expected = SpelEvaluationException.class) + @Test public void spelExpressionListNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aList.contains('one')"); - spelExpression.getValue(); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( + spelExpression::getValue); } - @Test(expected = SpelEvaluationException.class) + @Test public void spelExpressionListIndexAccessNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'"); - spelExpression.getValue(); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( + spelExpression::getValue); } @Test @@ -131,11 +136,12 @@ public class SpelExceptionTests { assertTrue(result); } - @Test(expected = SpelEvaluationException.class) + @Test public void spelExpressionArrayIndexAccessNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#anArray[0] eq 1"); - spelExpression.getValue(); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( + spelExpression::getValue); } @Test 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 44edfdb8fea..a22fe2e9c6c 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 @@ -60,7 +60,9 @@ import org.springframework.expression.spel.support.StandardTypeLocator; import org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver; 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; @@ -68,7 +70,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Reproduction tests cornering various reported SpEL issues. @@ -109,14 +110,9 @@ public class SpelReproTests extends AbstractExpressionTests { assertEquals(12, expr.getValue(context)); expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(null)"); assertEquals(null, expr.getValue(context)); - try { - expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)"); - expr.getValue(); - fail("Should have failed to find a method to which it could pass null"); - } - catch (EvaluationException see) { - // success - } + expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)"); + assertThatExceptionOfType(EvaluationException.class).isThrownBy( + expr::getValue); context.setTypeLocator(new MyTypeLocator()); // varargs @@ -243,22 +239,10 @@ public class SpelReproTests extends AbstractExpressionTests { EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); assertFalse(accessor.canRead(context, null, "abc")); assertFalse(accessor.canWrite(context, null, "abc")); - - try { - accessor.read(context, null, "abc"); - fail("Should have failed with an IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - - try { - accessor.write(context, null, "abc", "foo"); - fail("Should have failed with an IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + accessor.read(context, null, "abc")); + assertThatIllegalStateException().isThrownBy(() -> + accessor.write(context, null, "abc", "foo")); } @Test @@ -416,20 +400,15 @@ public class SpelReproTests extends AbstractExpressionTests { private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) { SpelExpressionParser parser = new SpelExpressionParser(); - try { - parser.parseExpression(expression, context); - fail("Should have failed with message: " + expectedMessage); - } - catch (Exception ex) { + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + parser.parseExpression(expression, context)) + .satisfies(ex -> { String message = ex.getMessage(); if (ex instanceof ExpressionException) { message = ((ExpressionException) ex).getSimpleMessage(); } - if (!message.equals(expectedMessage)) { - ex.printStackTrace(); - } - assertThat(expectedMessage, equalTo(message)); - } + assertThat(message).isEqualTo(expectedMessage); + }); } @@ -513,26 +492,16 @@ public class SpelReproTests extends AbstractExpressionTests { assertEquals(null, expr.getValue()); // Different parts of ternary expression are null - try { - expr = new SpelExpressionParser().parseRaw("(?'abc':'default')"); - expr.getValue(context); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.TYPE_CONVERSION_ERROR, see.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + new SpelExpressionParser().parseRaw("(?'abc':'default')").getValue(context)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_CONVERSION_ERROR)); expr = new SpelExpressionParser().parseRaw("(false?'abc':null)"); assertEquals(null, expr.getValue()); // Assignment - try { - expr = new SpelExpressionParser().parseRaw("(='default')"); - expr.getValue(context); - fail(); - } - catch (SpelEvaluationException see) { - assertEquals(SpelMessage.SETVALUE_NOT_SUPPORTED, see.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + new SpelExpressionParser().parseRaw("(='default')").getValue(context)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.SETVALUE_NOT_SUPPORTED)); } @Test @@ -1265,14 +1234,8 @@ public class SpelReproTests extends AbstractExpressionTests { public void SPR16123() { ExpressionParser parser = new SpelExpressionParser(); parser.parseExpression("simpleProperty").setValue(new BooleanHolder(), null); - - try { - parser.parseExpression("primitiveProperty").setValue(new BooleanHolder(), null); - fail("Should have thrown EvaluationException"); - } - catch (EvaluationException ex) { - // expected - } + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + parser.parseExpression("primitiveProperty").setValue(new BooleanHolder(), null)); } @Test @@ -1578,23 +1541,19 @@ public class SpelReproTests extends AbstractExpressionTests { expr = new SpelExpressionParser().parseRaw("&foo"); assertEquals("foo factory",expr.getValue(context)); - try { - expr = new SpelExpressionParser().parseRaw("&@foo"); - fail("Illegal syntax, error expected"); - } - catch (SpelParseException spe) { - assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode()); - assertEquals(0,spe.getPosition()); - } + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> + new SpelExpressionParser().parseRaw("&@foo")) + .satisfies(ex -> { + assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.INVALID_BEAN_REFERENCE); + assertThat(ex.getPosition()).isEqualTo(0); + }); - try { - expr = new SpelExpressionParser().parseRaw("@&foo"); - fail("Illegal syntax, error expected"); - } - catch (SpelParseException spe) { - assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode()); - assertEquals(0,spe.getPosition()); - } + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> + new SpelExpressionParser().parseRaw("@&foo")) + .satisfies(ex -> { + assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.INVALID_BEAN_REFERENCE); + assertThat(ex.getPosition()).isEqualTo(0); + }); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java index b8008fe45fb..95c93f90fe7 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java @@ -22,10 +22,11 @@ import org.junit.Test; import org.springframework.expression.EvaluationException; import org.springframework.expression.spel.support.StandardTypeLocator; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for type comparison @@ -49,14 +50,9 @@ public class StandardTypeLocatorTests { // currently does not know about java.util by default // assertEquals(java.util.List.class,locator.findType("List")); - try { - locator.findType("URL"); - fail("Should have failed"); - } - catch (EvaluationException ee) { - SpelEvaluationException sEx = (SpelEvaluationException)ee; - assertEquals(SpelMessage.TYPE_NOT_FOUND,sEx.getMessageCode()); - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + locator.findType("URL")) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_NOT_FOUND)); locator.registerImport("java.net"); assertEquals(java.net.URL.class,locator.findType("URL")); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java index fa8a43a6046..8ca249301c2 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java @@ -28,10 +28,11 @@ import org.springframework.expression.common.TemplateParserContext; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Andy Clement @@ -119,19 +120,19 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { public void testCompositeStringExpression() throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); Expression ex = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT); - checkString("hello world", ex.getValue()); - checkString("hello world", ex.getValue(String.class)); - checkString("hello world", ex.getValue((Object)null, String.class)); - checkString("hello world", ex.getValue(new Rooty())); - checkString("hello world", ex.getValue(new Rooty(), String.class)); + assertThat(ex.getValue()).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(String.class)).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue((Object)null, String.class)).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(new Rooty())).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world"); EvaluationContext ctx = new StandardEvaluationContext(); - checkString("hello world", ex.getValue(ctx)); - checkString("hello world", ex.getValue(ctx, String.class)); - checkString("hello world", ex.getValue(ctx, null, String.class)); - checkString("hello world", ex.getValue(ctx, new Rooty())); - checkString("hello world", ex.getValue(ctx, new Rooty(), String.class)); - checkString("hello world", ex.getValue(ctx, new Rooty(), String.class)); + assertThat(ex.getValue(ctx)).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(ctx, String.class)).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(ctx, null, String.class)).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(ctx, new Rooty())).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(ctx, new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world"); + assertThat(ex.getValue(ctx, new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world"); assertEquals("hello ${'world'}", ex.getExpressionString()); assertFalse(ex.isWritable(new StandardEvaluationContext())); assertFalse(ex.isWritable(new Rooty())); @@ -145,28 +146,12 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { assertEquals(String.class,ex.getValueType(ctx, new Rooty())); assertEquals(String.class,ex.getValueTypeDescriptor(new Rooty()).getType()); assertEquals(String.class,ex.getValueTypeDescriptor(ctx, new Rooty()).getType()); - - try { - ex.setValue(ctx, null); - fail(); - } - catch (EvaluationException ee) { - // success - } - try { - ex.setValue((Object)null, null); - fail(); - } - catch (EvaluationException ee) { - // success - } - try { - ex.setValue(ctx, null, null); - fail(); - } - catch (EvaluationException ee) { - // success - } + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + ex.setValue(ctx, null)); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + ex.setValue((Object)null, null)); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + ex.setValue(ctx, null, null)); } static class Rooty {} @@ -193,21 +178,13 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); assertEquals("hello 4 10 world",s); - try { - ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5] world",DEFAULT_TEMPLATE_PARSER_CONTEXT); - fail("Should have failed"); - } - catch (ParseException pe) { - assertEquals("No ending suffix '}' for expression starting at character 41: ${listOfNumbersUpToTen.$[#this>5] world", pe.getSimpleMessage()); - } + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5] world",DEFAULT_TEMPLATE_PARSER_CONTEXT)) + .satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("No ending suffix '}' for expression starting at character 41: ${listOfNumbersUpToTen.$[#this>5] world")); - try { - ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT); - fail("Should have failed"); - } - catch (ParseException pe) { - assertEquals("Found closing '}' at position 74 but most recent opening is '[' at position 30", pe.getSimpleMessage()); - } + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT)) + .satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("Found closing '}' at position 74 but most recent opening is '[' at position 30")); } @Test @@ -235,28 +212,18 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { @Test public void testErrorCases() throws Exception { - try { - parser.parseExpression("hello ${'world'", DEFAULT_TEMPLATE_PARSER_CONTEXT); - fail("Should have failed"); - } - catch (ParseException pe) { - assertEquals("No ending suffix '}' for expression starting at character 6: ${'world'", pe.getSimpleMessage()); - assertEquals("hello ${'world'", pe.getExpressionString()); - } - try { - parser.parseExpression("hello ${'wibble'${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT); - fail("Should have failed"); - } - catch (ParseException pe) { - assertEquals("No ending suffix '}' for expression starting at character 6: ${'wibble'${'world'}", pe.getSimpleMessage()); - } - try { - parser.parseExpression("hello ${} world", DEFAULT_TEMPLATE_PARSER_CONTEXT); - fail("Should have failed"); - } - catch (ParseException pe) { - assertEquals("No expression defined within delimiter '${}' at character 6", pe.getSimpleMessage()); - } + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + parser.parseExpression("hello ${'world'", DEFAULT_TEMPLATE_PARSER_CONTEXT)) + .satisfies(pex -> { + assertThat(pex.getSimpleMessage()).isEqualTo("No ending suffix '}' for expression starting at character 6: ${'world'"); + assertThat(pex.getExpressionString()).isEqualTo("hello ${'world'"); + }); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + parser.parseExpression("hello ${'wibble'${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT)) + .satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("No ending suffix '}' for expression starting at character 6: ${'wibble'${'world'}")); + assertThatExceptionOfType(ParseException.class).isThrownBy(() -> + parser.parseExpression("hello ${} world", DEFAULT_TEMPLATE_PARSER_CONTEXT)) + .satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("No expression defined within delimiter '${}' at character 6")); } @Test @@ -277,15 +244,4 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { assertTrue(pc.isTemplate()); } - // --- - - private void checkString(String expectedString, Object value) { - if (!(value instanceof String)) { - fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")"); - } - if (!value.equals(expectedString)) { - fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'"); - } - } - } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java index f09a4b3578a..7d3ed06930c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java @@ -21,7 +21,8 @@ import org.junit.Test; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests the evaluation of expressions that access variables and functions (lambda/java). @@ -74,18 +75,9 @@ public class VariableAndFunctionTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("notStatic", this.getClass().getMethod("nonStatic")); - try { - @SuppressWarnings("unused") - Object v = parser.parseRaw("#notStatic()").getValue(ctx); - fail("Should have failed with exception - cannot call non static method that way"); - } - catch (SpelEvaluationException se) { - if (se.getMessageCode() != SpelMessage.FUNCTION_MUST_BE_STATIC) { - se.printStackTrace(); - fail("Should have failed a message about the function needing to be static, not: " - + se.getMessageCode()); - } - } + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + parser.parseRaw("#notStatic()").getValue(ctx)). + satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.FUNCTION_MUST_BE_STATIC)); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java index 89f1ac12490..8acdb6cd9b3 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java @@ -30,6 +30,8 @@ import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.support.StandardTypeConverter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -42,19 +44,21 @@ import static org.junit.Assert.assertEquals; */ public class OpPlusTests { - @Test(expected = IllegalArgumentException.class) + @Test public void test_emptyOperands() { - new OpPlus(-1, -1); + assertThatIllegalArgumentException().isThrownBy(() -> + new OpPlus(-1, -1)); } - @Test(expected = SpelEvaluationException.class) + @Test public void test_unaryPlusWithStringLiteral() { ExpressionState expressionState = new ExpressionState(new StandardEvaluationContext()); StringLiteral str = new StringLiteral("word", -1, -1, "word"); OpPlus o = new OpPlus(-1, -1, str); - o.getValueInternal(expressionState); + assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> + o.getValueInternal(expressionState)); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java index eab6d8bbb79..582145eea14 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java @@ -16,11 +16,12 @@ package org.springframework.expression.spel.standard; +import java.util.function.Consumer; + import org.junit.Test; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionException; -import org.springframework.expression.ParseException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.SpelNode; import org.springframework.expression.spel.SpelParseException; @@ -28,12 +29,13 @@ import org.springframework.expression.spel.ast.OpAnd; import org.springframework.expression.spel.ast.OpOr; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Andy Clement @@ -116,86 +118,53 @@ public class SpelParserTests { @Test public void generalExpressions() { - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { SpelExpressionParser parser = new SpelExpressionParser(); parser.parseRaw("new String"); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(SpelMessage.MISSING_CONSTRUCTOR_ARGS, spe.getMessageCode()); - assertEquals(10, spe.getPosition()); - assertTrue(ex.getMessage().contains(ex.getExpressionString())); - } + }) + .satisfies(ex -> parseExceptionRequirements(SpelMessage.MISSING_CONSTRUCTOR_ARGS, 10)); - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { SpelExpressionParser parser = new SpelExpressionParser(); parser.parseRaw("new String(3,"); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode()); - assertEquals(10, spe.getPosition()); - assertTrue(ex.getMessage().contains(ex.getExpressionString())); - } + }) + .satisfies(ex -> parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10)); - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { SpelExpressionParser parser = new SpelExpressionParser(); parser.parseRaw("new String(3"); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode()); - assertEquals(10, spe.getPosition()); - assertTrue(ex.getMessage().contains(ex.getExpressionString())); - } + }) + .satisfies(ex -> parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10)); - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { SpelExpressionParser parser = new SpelExpressionParser(); parser.parseRaw("new String("); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode()); - assertEquals(10, spe.getPosition()); - assertTrue(ex.getMessage().contains(ex.getExpressionString())); - } + }) + .satisfies(ex -> parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10)); - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { SpelExpressionParser parser = new SpelExpressionParser(); parser.parseRaw("\"abc"); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, spe.getMessageCode()); - assertEquals(0, spe.getPosition()); - assertTrue(ex.getMessage().contains(ex.getExpressionString())); - } + }) + .satisfies(ex -> parseExceptionRequirements(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 0)); - try { + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> { SpelExpressionParser parser = new SpelExpressionParser(); parser.parseRaw("'abc"); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(SpelMessage.NON_TERMINATING_QUOTED_STRING, spe.getMessageCode()); - assertEquals(0, spe.getPosition()); - assertTrue(ex.getMessage().contains(ex.getExpressionString())); - } + }) + .satisfies(ex -> parseExceptionRequirements(SpelMessage.NON_TERMINATING_QUOTED_STRING, 0)); } + private Consumer parseExceptionRequirements( + SpelMessage expectedMessage, int expectedPosition) { + return ex -> { + assertThat(ex.getMessageCode()).isEqualTo(expectedMessage); + assertThat(ex.getPosition()).isEqualTo(expectedPosition); + assertThat(ex.getMessage()).contains(ex.getExpressionString()); + }; + } + @Test public void arithmeticPrecedence2() { SpelExpressionParser parser = new SpelExpressionParser(); @@ -287,14 +256,12 @@ public class SpelParserTests { @Test public void testStringLiterals_DoubleQuotes_spr9620_2() { - try { - new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\""); - fail("Should have failed"); - } - catch (SpelParseException spe) { - assertEquals(17, spe.getPosition()); - assertEquals(SpelMessage.UNEXPECTED_ESCAPE_CHAR, spe.getMessageCode()); - } + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> + new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\"")) + .satisfies(ex -> { + assertThat(ex.getPosition()).isEqualTo(17); + assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.UNEXPECTED_ESCAPE_CHAR); + }); } @Test @@ -417,21 +384,15 @@ public class SpelParserTests { assertEquals(type, exprVal.getClass()); } catch (Exception ex) { - fail(ex.getMessage()); + throw new AssertionError(ex.getMessage(), ex); } } private void checkNumberError(String expression, SpelMessage expectedMessage) { - try { - SpelExpressionParser parser = new SpelExpressionParser(); - parser.parseRaw(expression); - fail(); - } - catch (ParseException ex) { - assertTrue(ex instanceof SpelParseException); - SpelParseException spe = (SpelParseException) ex; - assertEquals(expectedMessage, spe.getMessageCode()); - } + SpelExpressionParser parser = new SpelExpressionParser(); + assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> + parser.parseRaw(expression)) + .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(expectedMessage)); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java index 22177d41948..fe839095bc2 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java @@ -34,13 +34,13 @@ import org.springframework.expression.spel.SpelUtilities; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.support.ReflectionHelper.ArgumentsMatchKind; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests for reflection helper code. @@ -329,83 +329,41 @@ public class ReflectionHelperTests extends AbstractExpressionTests { @Test public void testOptimalReflectivePropertyAccessor() throws Exception { - ReflectivePropertyAccessor rpa = new ReflectivePropertyAccessor(); - Tester t = new Tester(); - t.setProperty("hello"); - EvaluationContext ctx = new StandardEvaluationContext(t); - assertTrue(rpa.canRead(ctx, t, "property")); - assertEquals("hello", rpa.read(ctx, t, "property").getValue()); - assertEquals("hello", rpa.read(ctx, t, "property").getValue()); // cached accessor used + ReflectivePropertyAccessor reflective = new ReflectivePropertyAccessor(); + Tester tester = new Tester(); + tester.setProperty("hello"); + EvaluationContext ctx = new StandardEvaluationContext(tester); + assertTrue(reflective.canRead(ctx, tester, "property")); + assertEquals("hello", reflective.read(ctx, tester, "property").getValue()); + assertEquals("hello", reflective.read(ctx, tester, "property").getValue()); // cached accessor used - PropertyAccessor optA = rpa.createOptimalAccessor(ctx, t, "property"); - assertTrue(optA.canRead(ctx, t, "property")); - assertFalse(optA.canRead(ctx, t, "property2")); - try { - optA.canWrite(ctx, t, "property"); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - try { - optA.canWrite(ctx, t, "property2"); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - assertEquals("hello",optA.read(ctx, t, "property").getValue()); - assertEquals("hello",optA.read(ctx, t, "property").getValue()); // cached accessor used + PropertyAccessor property = reflective.createOptimalAccessor(ctx, tester, "property"); + assertTrue(property.canRead(ctx, tester, "property")); + assertFalse(property.canRead(ctx, tester, "property2")); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + property.canWrite(ctx, tester, "property")); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + property.canWrite(ctx, tester, "property2")); + assertEquals("hello",property.read(ctx, tester, "property").getValue()); + assertEquals("hello",property.read(ctx, tester, "property").getValue()); // cached accessor used + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + property.getSpecificTargetClasses()); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + property.write(ctx, tester, "property", null)); - try { - optA.getSpecificTargetClasses(); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - try { - optA.write(ctx, t, "property", null); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - - optA = rpa.createOptimalAccessor(ctx, t, "field"); - assertTrue(optA.canRead(ctx, t, "field")); - assertFalse(optA.canRead(ctx, t, "field2")); - try { - optA.canWrite(ctx, t, "field"); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - try { - optA.canWrite(ctx, t, "field2"); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - assertEquals(3,optA.read(ctx, t, "field").getValue()); - assertEquals(3,optA.read(ctx, t, "field").getValue()); // cached accessor used - - try { - optA.getSpecificTargetClasses(); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } - try { - optA.write(ctx, t, "field", null); - fail(); - } - catch (UnsupportedOperationException uoe) { - // success - } + PropertyAccessor field = reflective.createOptimalAccessor(ctx, tester, "field"); + assertTrue(field.canRead(ctx, tester, "field")); + assertFalse(field.canRead(ctx, tester, "field2")); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + field.canWrite(ctx, tester, "field")); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + field.canWrite(ctx, tester, "field2")); + assertEquals(3,field.read(ctx, tester, "field").getValue()); + assertEquals(3,field.read(ctx, tester, "field").getValue()); // cached accessor used + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + field.getSpecificTargetClasses()); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + field.write(ctx, tester, "field", null)); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java index c8ca8141114..96db109c74b 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java @@ -28,6 +28,7 @@ import org.springframework.expression.TypeComparator; import org.springframework.expression.TypeConverter; import org.springframework.expression.TypeLocator; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -48,11 +49,12 @@ public class StandardComponentsTests { assertEquals(tl, context.getTypeLocator()); } - @Test(expected = EvaluationException.class) + @Test public void testStandardOperatorOverloader() throws EvaluationException { OperatorOverloader oo = new StandardOperatorOverloader(); assertFalse(oo.overridesOperation(Operation.ADD, null, null)); - oo.operate(Operation.ADD, 2, 3); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + oo.operate(Operation.ADD, 2, 3)); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java index bc96d6e8e7d..26496f93137 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java @@ -29,6 +29,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -66,11 +67,12 @@ public class InitializeDatabaseIntegrationTests { assertCorrectSetup(context.getBean("dataSource", DataSource.class)); } - @Test(expected = BadSqlGrammarException.class) + @Test public void testDisableCreateEmbeddedDatabase() throws Exception { System.setProperty("ENABLED", "false"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml"); - assertCorrectSetup(context.getBean("dataSource", DataSource.class)); + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> + assertCorrectSetup(context.getBean("dataSource", DataSource.class))); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java index 8d5b073edfa..80e78733b11 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java @@ -28,6 +28,7 @@ import org.junit.Test; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.dao.TypeMismatchDataAccessException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.BDDMockito.given; @@ -84,7 +85,7 @@ public class SingleColumnRowMapperTests { assertEquals(timestamp.toLocalDateTime(), actualMyLocalDateTime.value); } - @Test(expected = TypeMismatchDataAccessException.class) // SPR-16483 + @Test // SPR-16483 public void doesNotUseConversionService() throws SQLException { SingleColumnRowMapper rowMapper = SingleColumnRowMapper.newInstance(LocalDateTime.class, null); @@ -96,8 +97,8 @@ public class SingleColumnRowMapperTests { given(resultSet.getObject(1, LocalDateTime.class)) .willThrow(new SQLFeatureNotSupportedException()); given(resultSet.getTimestamp(1)).willReturn(new Timestamp(0)); - - rowMapper.mapRow(resultSet, 1); + assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> + rowMapper.mapRow(resultSet, 1)); } 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 dff3ebed793..d94a477ecd0 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 @@ -24,6 +24,7 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; +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; @@ -37,15 +38,17 @@ import static org.junit.Assert.assertTrue; */ public class BeanPropertySqlParameterSourceTests { - @Test(expected = IllegalArgumentException.class) + @Test public void withNullBeanPassedToCtor() { - new BeanPropertySqlParameterSource(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new BeanPropertySqlParameterSource(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void getValueWhereTheUnderlyingBeanHasNoSuchProperty() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean()); - source.getValue("thisPropertyDoesNotExist"); + assertThatIllegalArgumentException().isThrownBy(() -> + source.getValue("thisPropertyDoesNotExist")); } @Test @@ -75,10 +78,11 @@ public class BeanPropertySqlParameterSourceTests { assertFalse(source.hasValue("thisPropertyDoesNotExist")); } - @Test(expected = IllegalArgumentException.class) + @Test public void getValueWhereTheUnderlyingBeanPropertyIsNotReadable() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties()); - source.getValue("noOp"); + assertThatIllegalArgumentException().isThrownBy(() -> + source.getValue("noOp")); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java index f12eee42b42..97f59531e74 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.support.JdbcUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -37,10 +38,11 @@ public class MapSqlParameterSourceTests { new MapSqlParameterSource(null); } - @Test(expected = IllegalArgumentException.class) + @Test public void getValueChokesIfParameterIsNotPresent() { MapSqlParameterSource source = new MapSqlParameterSource(); - source.getValue("pechorin was right!"); + assertThatIllegalArgumentException().isThrownBy(() -> + source.getValue("pechorin was right!")); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java index cb7874f38b2..ed8ea39df09 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java @@ -24,9 +24,9 @@ import org.junit.Test; import org.springframework.dao.InvalidDataAccessApiUsageException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Thomas Risberg @@ -80,12 +80,8 @@ public class NamedParameterUtilsTests { assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap).length); assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :a :a xx :a :a", paramMap).length); assertEquals("b", NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap)[4]); - try { - NamedParameterUtils.buildValueArray("xxx :a :b ?", paramMap); - fail("mixed named parameters and ? placeholders not detected"); - } - catch (InvalidDataAccessApiUsageException expected) { - } + assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).as("mixed named parameters and ? placeholders").isThrownBy(() -> + NamedParameterUtils.buildValueArray("xxx :a :b ?", paramMap)); } @Test @@ -118,10 +114,11 @@ public class NamedParameterUtilsTests { .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).get(2).getTypeName()); } - @Test(expected = InvalidDataAccessApiUsageException.class) + @Test public void buildValueArrayWithMissingParameterValue() { String sql = "select count(0) from foo where id = :id"; - NamedParameterUtils.buildValueArray(sql, Collections.emptyMap()); + assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> + NamedParameterUtils.buildValueArray(sql, Collections.emptyMap())); } @Test 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 7d8580d8e3e..b5a4b6bdbcf 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 @@ -35,7 +35,6 @@ import org.springframework.jdbc.support.lob.LobHandler; 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.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -141,14 +140,9 @@ public class SqlLobValueTests { SqlLobValue lob = new SqlLobValue("bla"); lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test"); - try { - lob = new SqlLobValue("bla".getBytes()); - lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test"); - fail("IllegalArgumentException should have been thrown"); - } - catch (IllegalArgumentException e) { - // expected - } + SqlLobValue lob2 = new SqlLobValue("bla".getBytes()); + assertThatIllegalArgumentException().isThrownBy(() -> + lob2.setTypeValue(preparedStatement, 1, Types.CLOB, "test")); lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3); lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test"); @@ -167,16 +161,10 @@ public class SqlLobValueTests { lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3); lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test"); - lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream( + SqlLobValue lob3 = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream( "bla".getBytes())), 3); - - try { - lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test"); - fail("IllegalArgumentException should have been thrown"); - } - catch (IllegalArgumentException e) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + lob3.setTypeValue(preparedStatement, 1, Types.BLOB, "test")); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java index d423460fa96..f5714ca0b39 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java @@ -46,11 +46,11 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.atLeastOnce; @@ -475,8 +475,9 @@ public class DataSourceJtaTransactionTests { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(TransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { + @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); @@ -527,13 +528,7 @@ public class DataSourceJtaTransactionTests { } } } - }); - - fail("Should have thrown TransactionException"); - } - catch (TransactionException ex) { - // expected - } + })); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java index 6ed1b4ef109..34062b11213 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java @@ -48,6 +48,8 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -225,31 +227,26 @@ public class DataSourceTransactionManagerTests { assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); final RuntimeException ex = new RuntimeException("Application exception"); - try { - tt.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); - Connection con = DataSourceUtils.getConnection(dsToUse); - if (createStatement) { - try { - con.createStatement(); - } - catch (SQLException ex) { - throw new UncategorizedSQLException("", "", ex); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + tt.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { + assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); + assertTrue("Is new transaction", status.isNewTransaction()); + Connection con = DataSourceUtils.getConnection(dsToUse); + if (createStatement) { + try { + con.createStatement(); + } + catch (SQLException ex) { + throw new UncategorizedSQLException("", "", ex); + } } + throw ex; } - throw ex; - } - }); - fail("Should have thrown RuntimeException"); - } - catch (RuntimeException ex2) { - // expected - assertTrue("Correct exception thrown", ex2.equals(ex)); - } + })) + .isEqualTo(ex); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); @@ -384,31 +381,26 @@ public class DataSourceTransactionManagerTests { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); - try { - final TransactionTemplate tt = new TransactionTemplate(tm); - final TransactionTemplate tt2 = new TransactionTemplate(tm); - tt2.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> { + final TransactionTemplate tt = new TransactionTemplate(tm); + final TransactionTemplate tt2 = new TransactionTemplate(tm); + tt2.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - tt.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertFalse("Is not rollback-only", status.isRollbackOnly()); - tt2.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - status.setRollbackOnly(); - } - }); - assertTrue("Is rollback-only", status.isRollbackOnly()); - } + tt.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { + assertFalse("Is not rollback-only", status.isRollbackOnly()); + tt2.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { + status.setRollbackOnly(); + } + }); + assertTrue("Is rollback-only", status.isRollbackOnly()); + } + }); }); - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).rollback(); verify(con).close(); @@ -422,7 +414,7 @@ public class DataSourceTransactionManagerTests { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setReadOnly(true); final TransactionTemplate tt2 = new TransactionTemplate(tm); @@ -441,12 +433,7 @@ public class DataSourceTransactionManagerTests { assertTrue("Is rollback-only", status.isRollbackOnly()); } }); - - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } + }); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).rollback(); @@ -546,9 +533,8 @@ public class DataSourceTransactionManagerTests { final TestTransactionSynchronization synch = new TestTransactionSynchronization(ds, TransactionSynchronization.STATUS_UNKNOWN); - try { + assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> { assertTrue("Is new transaction", ts.isNewTransaction()); - final TransactionTemplate tt = new TransactionTemplate(tm2); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -571,12 +557,7 @@ public class DataSourceTransactionManagerTests { }); tm.commit(ts); - - fail("Should have thrown UnexpectedRollbackException"); - } - catch (UnexpectedRollbackException ex) { - // expected - } + }); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertFalse(synch.beforeCommitCalled); @@ -692,7 +673,7 @@ public class DataSourceTransactionManagerTests { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds2)); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { @@ -707,12 +688,7 @@ public class DataSourceTransactionManagerTests { } }); } - }); - fail("Should have thrown CannotCreateTransactionException"); - } - catch (CannotCreateTransactionException ex) { - assertSame(failure, ex.getCause()); - } + })).withCause(failure); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds2)); @@ -763,7 +739,7 @@ public class DataSourceTransactionManagerTests { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { @@ -777,11 +753,7 @@ public class DataSourceTransactionManagerTests { }); fail("Should have thrown IllegalTransactionStateException"); } - }); - } - catch (IllegalTransactionStateException ex) { - // expected - } + })); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).rollback(); @@ -1143,18 +1115,13 @@ public class DataSourceTransactionManagerTests { willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit(); TransactionTemplate tt = new TransactionTemplate(tm); - try { + assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional } - }); - fail("Should have thrown CannotCreateTransactionException"); - } - catch (CannotCreateTransactionException ex) { - // expected - } + })); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).close(); @@ -1165,18 +1132,13 @@ public class DataSourceTransactionManagerTests { willThrow(new SQLException("Cannot commit")).given(con).commit(); TransactionTemplate tt = new TransactionTemplate(tm); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional } - }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + })); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).close(); @@ -1188,18 +1150,13 @@ public class DataSourceTransactionManagerTests { tm.setRollbackOnCommitFailure(true); TransactionTemplate tt = new TransactionTemplate(tm); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional } - }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + })); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).rollback(); @@ -1212,18 +1169,13 @@ public class DataSourceTransactionManagerTests { willThrow(new SQLException("Cannot rollback")).given(con).rollback(); TransactionTemplate tt = new TransactionTemplate(tm); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { status.setRollbackOnly(); } - }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + })); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); InOrder ordered = inOrder(con); @@ -1398,7 +1350,7 @@ public class DataSourceTransactionManagerTests { protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Is new transaction", status.isNewTransaction()); assertTrue("Isn't nested transaction", !status.hasSavepoint()); - try { + assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { @@ -1418,12 +1370,7 @@ public class DataSourceTransactionManagerTests { } }); } - }); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + })); assertTrue("Is new transaction", status.isNewTransaction()); assertTrue("Isn't nested transaction", !status.hasSavepoint()); } @@ -1456,7 +1403,7 @@ public class DataSourceTransactionManagerTests { protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Is new transaction", status.isNewTransaction()); assertTrue("Isn't nested transaction", !status.hasSavepoint()); - try { + assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { @@ -1476,12 +1423,7 @@ public class DataSourceTransactionManagerTests { } }); } - }); - fail("Should have thrown UnexpectedRollbackException"); - } - catch (UnexpectedRollbackException ex) { - // expected - } + })); assertTrue("Is new transaction", status.isNewTransaction()); assertTrue("Isn't nested transaction", !status.hasSavepoint()); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java index 673702a20af..4edbf49ae54 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java @@ -21,9 +21,9 @@ import java.util.Properties; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -139,14 +139,9 @@ public class DriverManagerDataSourceTests { public void testInvalidClassName() throws Exception { String bogusClassName = "foobar"; DriverManagerDataSource ds = new DriverManagerDataSource(); - try { - ds.setDriverClassName(bogusClassName); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // OK - assertTrue(ex.getCause() instanceof ClassNotFoundException); - } + assertThatIllegalStateException().isThrownBy(() -> + ds.setDriverClassName(bogusClassName)) + .withCauseInstanceOf(ClassNotFoundException.class); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java index 4c378ebb84b..3c67ebb1d24 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java @@ -23,8 +23,8 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.CannotReadScriptException; import org.springframework.jdbc.datasource.init.ScriptStatementFailedException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.DERBY; import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2; @@ -54,9 +54,10 @@ public class EmbeddedDatabaseBuilderTests { }); } - @Test(expected = CannotReadScriptException.class) + @Test public void addScriptWithBogusFileName() { - new EmbeddedDatabaseBuilder().addScript("bogus.sql").build(); + assertThatExceptionOfType(CannotReadScriptException.class).isThrownBy( + new EmbeddedDatabaseBuilder().addScript("bogus.sql")::build); } @Test @@ -165,17 +166,11 @@ public class EmbeddedDatabaseBuilderTests { @Test public void createSameSchemaTwiceWithoutUniqueDbNames() throws Exception { - EmbeddedDatabase db1 = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()))// - .addScripts("db-schema-without-dropping.sql").build(); - + EmbeddedDatabase db1 = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())) + .addScripts("db-schema-without-dropping.sql").build(); try { - new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()))// - .addScripts("db-schema-without-dropping.sql").build(); - - fail("Should have thrown a ScriptStatementFailedException"); - } - catch (ScriptStatementFailedException e) { - // expected + assertThatExceptionOfType(ScriptStatementFailedException.class).isThrownBy(() -> + new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())).addScripts("db-schema-without-dropping.sql").build()); } finally { db1.shutdown(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java index 56d6588e161..02065a93035 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java @@ -21,6 +21,7 @@ import org.mockito.Mockito; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -37,14 +38,16 @@ public class ResourceDatabasePopulatorTests { private static final Resource script3 = Mockito.mock(Resource.class); - @Test(expected = IllegalArgumentException.class) + @Test public void constructWithNullResource() { - new ResourceDatabasePopulator((Resource) null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ResourceDatabasePopulator((Resource) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructWithNullResourceArray() { - new ResourceDatabasePopulator((Resource[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ResourceDatabasePopulator((Resource[]) null)); } @Test @@ -68,28 +71,32 @@ public class ResourceDatabasePopulatorTests { assertEquals(3, databasePopulator.scripts.size()); } - @Test(expected = IllegalArgumentException.class) + @Test public void addScriptsWithNullResource() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - databasePopulator.addScripts((Resource) null); + assertThatIllegalArgumentException().isThrownBy(() -> + databasePopulator.addScripts((Resource) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void addScriptsWithNullResourceArray() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - databasePopulator.addScripts((Resource[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + databasePopulator.addScripts((Resource[]) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setScriptsWithNullResource() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - databasePopulator.setScripts((Resource) null); + assertThatIllegalArgumentException().isThrownBy(() -> + databasePopulator.setScripts((Resource) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setScriptsWithNullResourceArray() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - databasePopulator.setScripts((Resource[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + databasePopulator.setScripts((Resource[]) null)); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java index 35fc53c2a9e..12b464af609 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java @@ -23,9 +23,10 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -62,18 +63,16 @@ public class BeanFactoryDataSourceLookupTests { new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class)); - try { - BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory); - lookup.getDataSource(DATASOURCE_BEAN_NAME); - fail("should have thrown DataSourceLookupFailureException"); - } - catch (DataSourceLookupFailureException ex) { /* expected */ } + BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory); + assertThatExceptionOfType(DataSourceLookupFailureException.class).isThrownBy(() -> + lookup.getDataSource(DATASOURCE_BEAN_NAME)); } - @Test(expected = IllegalStateException.class) + @Test public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception { BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(); - lookup.getDataSource(DATASOURCE_BEAN_NAME); + assertThatIllegalStateException().isThrownBy(() -> + lookup.getDataSource(DATASOURCE_BEAN_NAME)); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java index c0e4c116cd3..bd04f50c99d 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java @@ -21,6 +21,7 @@ import javax.sql.DataSource; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -48,7 +49,7 @@ public class JndiDataSourceLookupTests { assertSame(expectedDataSource, dataSource); } - @Test(expected = DataSourceLookupFailureException.class) + @Test public void testNoDataSourceAtJndiLocation() throws Exception { JndiDataSourceLookup lookup = new JndiDataSourceLookup() { @Override @@ -57,7 +58,8 @@ public class JndiDataSourceLookupTests { throw new NamingException(); } }; - lookup.getDataSource(DATA_SOURCE_NAME); + assertThatExceptionOfType(DataSourceLookupFailureException.class).isThrownBy(() -> + lookup.getDataSource(DATA_SOURCE_NAME)); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java index 8cbb74fddbe..bd148cc6f83 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java @@ -28,6 +28,7 @@ import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.UncategorizedSQLException; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -46,9 +47,10 @@ public class SQLStateSQLExceptionTranslatorTests { private static final String SQL = "select count(0) from t_sheep where over_fence = ... yawn... 1"; - @Test(expected = IllegalArgumentException.class) + @Test public void testTranslateNullException() throws Exception { - new SQLStateSQLExceptionTranslator().translate("", "", null); + assertThatIllegalArgumentException().isThrownBy(() -> + new SQLStateSQLExceptionTranslator().translate("", "", null)); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java index b6e0c820208..b7f5d78cefc 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java @@ -30,8 +30,8 @@ import org.junit.Test; import org.springframework.jdbc.InvalidResultSetAccessException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -215,13 +215,9 @@ public class ResultSetWrappingRowSetTests { given(rsetMethod.invoke(resultSet, arg)).willReturn(ret).willThrow(new SQLException("test")); } rowsetMethod.invoke(rowSet, arg); - try { - rowsetMethod.invoke(rowSet, arg); - fail("InvalidResultSetAccessException should have been thrown"); - } - catch (InvocationTargetException ex) { - assertEquals(InvalidResultSetAccessException.class, ex.getTargetException().getClass()); - } + assertThatExceptionOfType(InvocationTargetException.class).isThrownBy(() -> + rowsetMethod.invoke(rowSet, arg)). + satisfies(ex -> assertThat(ex.getTargetException()).isExactlyInstanceOf(InvalidResultSetAccessException.class)); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java index 5efdfc9c5c7..9c8ed75678c 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java @@ -38,11 +38,11 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -167,13 +167,8 @@ public class JmsTransactionManagerTests { status.setRollbackOnly(); } }); - try { - tm.commit(ts); - fail("Should have thrown UnexpectedRollbackException"); - } - catch (UnexpectedRollbackException ex) { - // expected - } + assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> + tm.commit(ts)); verify(session).rollback(); verify(session).close(); diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java index 8ad82f49ed5..ba8afe6cf27 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java @@ -60,10 +60,10 @@ import org.springframework.jndi.JndiTemplate; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -800,15 +800,9 @@ public class JmsTemplateTests { willThrow(original).given(messageProducer).send(textMessage); - try { - template.convertAndSend(this.queue, s); - fail("Should have thrown JmsException"); - } - catch (JmsException wrappedEx) { - // expected - assertEquals(thrownExceptionClass, wrappedEx.getClass()); - assertEquals(original, wrappedEx.getCause()); - } + assertThatExceptionOfType(thrownExceptionClass).isThrownBy(() -> + template.convertAndSend(this.queue, s)) + .withCause(original); verify(messageProducer).close(); verify(this.session).close(); diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java index 126010339d4..d50501fe4b1 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java @@ -35,6 +35,7 @@ import org.springframework.jms.StubQueue; import org.springframework.lang.Nullable; import org.springframework.util.ErrorHandler; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -67,9 +68,10 @@ public class SimpleMessageListenerContainerTests { assertNull(this.container.getMessageListener()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSettingMessageListenerToAnUnsupportedType() { - this.container.setMessageListener("Bingo"); + assertThatIllegalArgumentException().isThrownBy(() -> + this.container.setMessageListener("Bingo")); } @Test @@ -80,16 +82,20 @@ public class SimpleMessageListenerContainerTests { this.container.isPubSubNoLocal()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSettingConcurrentConsumersToZeroIsNotAllowed() { - this.container.setConcurrentConsumers(0); - this.container.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy(() -> { + this.container.setConcurrentConsumers(0); + this.container.afterPropertiesSet(); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSettingConcurrentConsumersToANegativeValueIsNotAllowed() { - this.container.setConcurrentConsumers(-198); - this.container.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy(() -> { + this.container.setConcurrentConsumers(-198); + this.container.afterPropertiesSet(); + }); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java index 6647ff9b7f3..a861810ca78 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java @@ -37,12 +37,12 @@ import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -312,13 +312,9 @@ public class MessageListenerAdapterTests { return message; } }; - try { - adapter.onMessage(sentTextMessage, session); - fail("expected CouldNotSendReplyException with InvalidDestinationException"); - } - catch (ReplyFailureException ex) { - assertEquals(InvalidDestinationException.class, ex.getCause().getClass()); - } + assertThatExceptionOfType(ReplyFailureException.class).isThrownBy(() -> + adapter.onMessage(sentTextMessage, session)) + .withCauseExactlyInstanceOf(InvalidDestinationException.class); verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); verify(delegate).handleMessage(sentTextMessage); @@ -351,13 +347,9 @@ public class MessageListenerAdapterTests { return message; } }; - try { - adapter.onMessage(sentTextMessage, session); - fail("expected CouldNotSendReplyException with JMSException"); - } - catch (ReplyFailureException ex) { - assertEquals(JMSException.class, ex.getCause().getClass()); - } + assertThatExceptionOfType(ReplyFailureException.class).isThrownBy(() -> + adapter.onMessage(sentTextMessage, session)) + .withCauseExactlyInstanceOf(JMSException.class); verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); verify(messageProducer).close(); @@ -378,11 +370,8 @@ public class MessageListenerAdapterTests { return message; } }; - try { - adapter.onMessage(message, session); - fail("expected ListenerExecutionFailedException"); - } - catch (ListenerExecutionFailedException ex) { /* expected */ } + assertThatExceptionOfType(ListenerExecutionFailedException.class).isThrownBy(() -> + adapter.onMessage(message, session)); } @Test @@ -399,13 +388,9 @@ public class MessageListenerAdapterTests { } }; adapter.setMessageConverter(null); - try { - adapter.onMessage(sentTextMessage, session); - fail("expected CouldNotSendReplyException with MessageConversionException"); - } - catch (ReplyFailureException ex) { - assertEquals(MessageConversionException.class, ex.getCause().getClass()); - } + assertThatExceptionOfType(ReplyFailureException.class).isThrownBy(() -> + adapter.onMessage(sentTextMessage, session)) + .withCauseExactlyInstanceOf(MessageConversionException.class); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java index 3f42cf06375..87710b6c589 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java @@ -45,10 +45,11 @@ import org.springframework.messaging.handler.annotation.support.DefaultMessageHa import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -100,18 +101,10 @@ public class MessagingMessageListenerAdapterTests { javax.jms.Message message = new StubTextMessage("foo"); Session session = mock(Session.class); MessagingMessageListenerAdapter listener = getSimpleInstance("fail", String.class); - - try { - listener.onMessage(message, session); - fail("Should have thrown an exception"); - } - catch (JMSException ex) { - fail("Should not have thrown a JMS exception"); - } - catch (ListenerExecutionFailedException ex) { - assertEquals(IllegalArgumentException.class, ex.getCause().getClass()); - assertEquals("Expected test exception", ex.getCause().getMessage()); - } + assertThatExceptionOfType(ListenerExecutionFailedException.class).isThrownBy(() -> + listener.onMessage(message, session)) + .withCauseExactlyInstanceOf(IllegalArgumentException.class) + .satisfies(ex -> assertThat(ex.getCause().getMessage()).isEqualTo("Expected test exception")); } @Test @@ -120,16 +113,9 @@ public class MessagingMessageListenerAdapterTests { Session session = mock(Session.class); MessagingMessageListenerAdapter listener = getSimpleInstance("wrongParam", Integer.class); - try { - listener.onMessage(message, session); - fail("Should have thrown an exception"); - } - catch (JMSException ex) { - fail("Should not have thrown a JMS exception"); - } - catch (ListenerExecutionFailedException ex) { - assertEquals(MessageConversionException.class, ex.getCause().getClass()); - } + assertThatExceptionOfType(ListenerExecutionFailedException.class).isThrownBy(() -> + listener.onMessage(message, session)) + .withCauseExactlyInstanceOf(MessageConversionException.class); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java index e45b32b437c..b355795e14b 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java @@ -20,6 +20,7 @@ import javax.jms.Session; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -31,10 +32,11 @@ import static org.junit.Assert.assertFalse; */ public class JmsAccessorTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testChokesIfConnectionFactoryIsNotSupplied() throws Exception { JmsAccessor accessor = new StubJmsAccessor(); - accessor.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + accessor::afterPropertiesSet); } @Test @@ -56,9 +58,10 @@ public class JmsAccessorTests { accessor.getSessionAcknowledgeMode()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetAcknowledgeModeNameChokesIfBadAckModeIsSupplied() throws Exception { - new StubJmsAccessor().setSessionAcknowledgeModeName("Tally ho chaps!"); + assertThatIllegalArgumentException().isThrownBy(() -> + new StubJmsAccessor().setSessionAcknowledgeModeName("Tally ho chaps!")); } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java index 180b1fe9c78..10bba348ffa 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java @@ -35,9 +35,9 @@ import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -129,14 +129,16 @@ public class SimpleMessageConverterTests { assertEquals(content, converter.fromMessage(msg)); } - @Test(expected = MessageConversionException.class) + @Test public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception { - new SimpleMessageConverter().toMessage(null, null); + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + new SimpleMessageConverter().toMessage(null, null)); } - @Test(expected = MessageConversionException.class) + @Test public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception { - new SimpleMessageConverter().toMessage(new Object(), null); + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + new SimpleMessageConverter().toMessage(new Object(), null)); } @Test @@ -168,11 +170,8 @@ public class SimpleMessageConverterTests { content.put(1, "value1"); SimpleMessageConverter converter = new SimpleMessageConverter(); - try { - converter.toMessage(content, session); - fail("expected MessageConversionException"); - } - catch (MessageConversionException ex) { /* expected */ } + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + converter.toMessage(content, session)); } @Test @@ -185,11 +184,8 @@ public class SimpleMessageConverterTests { content.put(null, "value1"); SimpleMessageConverter converter = new SimpleMessageConverter(); - try { - converter.toMessage(content, session); - fail("expected MessageConversionException"); - } - catch (MessageConversionException ex) { /* expected */ } + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + converter.toMessage(content, session)); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java index 81b0242a789..388e4282f33 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java @@ -20,8 +20,8 @@ import javax.jms.ConnectionFactory; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -34,17 +34,10 @@ public class JmsDestinationAccessorTests { public void testChokesIfDestinationResolverIsetToNullExplicitly() throws Exception { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); - try { - JmsDestinationAccessor accessor = new StubJmsDestinationAccessor(); - accessor.setConnectionFactory(connectionFactory); - accessor.setDestinationResolver(null); - accessor.afterPropertiesSet(); - fail("expected IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } - + JmsDestinationAccessor accessor = new StubJmsDestinationAccessor(); + accessor.setConnectionFactory(connectionFactory); + assertThatIllegalArgumentException().isThrownBy(() -> + accessor.setDestinationResolver(null)); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java index e739f92ecf6..b90336a2bff 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java @@ -24,10 +24,11 @@ import org.junit.Test; import org.springframework.jms.StubTopic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -107,13 +108,8 @@ public class JndiDestinationResolverTests { }; resolver.setDynamicDestinationResolver(dynamicResolver); - try { - resolver.resolveDestinationName(session, DESTINATION_NAME, true); - fail("expected DestinationResolutionException"); - } - catch (DestinationResolutionException ex) { - // expected - } + assertThatExceptionOfType(DestinationResolutionException.class).isThrownBy(() -> + resolver.resolveDestinationName(session, DESTINATION_NAME, true)); } @@ -123,9 +119,7 @@ public class JndiDestinationResolverTests { @Override protected T lookup(String jndiName, Class requiredType) throws NamingException { - if (called) { - fail("Must not be delegating to lookup(..), must be resolving from cache."); - } + assertThat(called).as("delegating to lookup(..) not cache").isFalse(); assertEquals(DESTINATION_NAME, jndiName); called = true; return requiredType.cast(DESTINATION); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java b/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java index 5c67c33c051..a9786bef3d6 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; @@ -127,13 +128,14 @@ public class MessageHeadersTests { assertEquals(value, headers.get("test", Integer.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testHeaderValueAccessWithIncorrectType() { Integer value = new Integer(123); Map map = new HashMap<>(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertEquals(value, headers.get("test", String.class)); + assertThatIllegalArgumentException().isThrownBy(() -> + headers.get("test", String.class)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java index 995231caf0d..e4d8e2ae7a4 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java @@ -27,6 +27,8 @@ import org.springframework.messaging.MessageHeaders; import org.springframework.util.InvalidMimeTypeException; import org.springframework.util.MimeTypeUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -63,20 +65,22 @@ public class DefaultContentTypeResolverTests { assertEquals(MimeTypeUtils.APPLICATION_JSON, this.resolver.resolve(headers)); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void resolveInvalidStringContentType() { Map map = new HashMap<>(); map.put(MessageHeaders.CONTENT_TYPE, "invalidContentType"); MessageHeaders headers = new MessageHeaders(map); - this.resolver.resolve(headers); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + this.resolver.resolve(headers)); } - @Test(expected = IllegalArgumentException.class) + @Test public void resolveUnknownHeaderType() { Map map = new HashMap<>(); map.put(MessageHeaders.CONTENT_TYPE, new Integer(1)); MessageHeaders headers = new MessageHeaders(map); - this.resolver.resolve(headers); + assertThatIllegalArgumentException().isThrownBy(() -> + this.resolver.resolve(headers)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java index e7b67810494..44d010d0ba5 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,6 +33,7 @@ import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.MimeType; +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; @@ -127,12 +128,13 @@ public class MappingJackson2MessageConverterTests { assertSame(myBean, converter.fromMessage(message, MyBean.class)); } - @Test(expected = MessageConversionException.class) + @Test public void fromMessageInvalidJson() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "FooBar"; Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); - converter.fromMessage(message, MyBean.class); + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + converter.fromMessage(message, MyBean.class)); } @Test 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 8fbd33eb699..f54fadf84e2 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 @@ -28,6 +28,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +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; @@ -65,18 +66,20 @@ public class MarshallingMessageConverterTests { assertEquals("Foo", actual.getName()); } - @Test(expected = MessageConversionException.class) + @Test public void fromMessageInvalidXml() throws Exception { String payload = "Foo"; Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); - this.converter.fromMessage(message, MyBean.class); + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + this.converter.fromMessage(message, MyBean.class)); } - @Test(expected = MessageConversionException.class) + @Test public void fromMessageValidXmlWithUnknownProperty() throws IOException { String payload = "42"; Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); - this.converter.fromMessage(message, MyBean.class); + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + this.converter.fromMessage(message, MyBean.class)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java index 8b486bbb071..3169a826765 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java @@ -33,6 +33,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -104,10 +105,11 @@ public class MessageConverterTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void setStrictContentTypeMatchWithNoSupportedMimeTypes() { this.converter = new TestMessageConverter(Collections.emptyList()); - this.converter.setStrictContentTypeMatch(true); + assertThatIllegalArgumentException().isThrownBy(() -> + this.converter.setStrictContentTypeMatch(true)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java index 9eb057939dc..6f8d1d4ecae 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java @@ -18,6 +18,7 @@ package org.springframework.messaging.core; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -50,15 +51,17 @@ public class CachingDestinationResolverTests { verify(resolver, times(1)).resolveDestination("1234"); } - @Test(expected = IllegalArgumentException.class) + @Test public void noTargetSet() { CachingDestinationResolverProxy resolverProxy = new CachingDestinationResolverProxy<>(); - resolverProxy.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + resolverProxy::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) + @Test public void nullTargetThroughConstructor() { - new CachingDestinationResolverProxy(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new CachingDestinationResolverProxy(null)); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java index 2a2ed57758a..a53e6e49dfb 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java @@ -28,6 +28,7 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.messaging.support.GenericMessage; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -74,10 +75,11 @@ public class DestinationResolvingMessagingTemplateTests { assertSame(message, this.template.message); } - @Test(expected = IllegalStateException.class) + @Test public void sendNoDestinationResolver() { TestDestinationResolvingMessagingTemplate template = new TestDestinationResolvingMessagingTemplate(); - template.send("myChannel", new GenericMessage("payload")); + assertThatIllegalStateException().isThrownBy(() -> + template.send("myChannel", new GenericMessage("payload"))); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java index 64c5b63913e..58c4198ad31 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java @@ -28,6 +28,7 @@ import org.springframework.messaging.converter.MessageConversionException; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -59,9 +60,10 @@ public class MessageReceivingTemplateTests { assertSame(expected, actual); } - @Test(expected = IllegalStateException.class) + @Test public void receiveMissingDefaultDestination() { - this.template.receive(); + assertThatIllegalStateException().isThrownBy( + this.template::receive); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java index c65e50dc459..9cf965ab30c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -65,9 +66,10 @@ public class MessageRequestReplyTemplateTests { assertSame(responseMessage, actual); } - @Test(expected = IllegalStateException.class) + @Test public void sendAndReceiveMissingDestination() { - this.template.sendAndReceive(new GenericMessage("request")); + assertThatIllegalStateException().isThrownBy(() -> + this.template.sendAndReceive(new GenericMessage("request"))); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java index 74add25f265..b79e5792831 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java @@ -36,6 +36,8 @@ import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -81,10 +83,11 @@ public class MessageSendingTemplateTests { assertSame(message, this.template.message); } - @Test(expected = IllegalStateException.class) + @Test public void sendMissingDestination() { Message message = new GenericMessage("payload"); - this.template.send(message); + assertThatIllegalStateException().isThrownBy(() -> + this.template.send(message)); } @Test @@ -174,7 +177,7 @@ public class MessageSendingTemplateTests { assertSame(this.template.message, this.postProcessor.getMessage()); } - @Test(expected = MessageConversionException.class) + @Test public void convertAndSendNoMatchingConverter() { MessageConverter converter = new CompositeMessageConverter( @@ -182,7 +185,8 @@ public class MessageSendingTemplateTests { this.template.setMessageConverter(converter); this.headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_XML); - this.template.convertAndSend("home", "payload", new MessageHeaders(this.headers)); + assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> + this.template.convertAndSend("home", "payload", new MessageHeaders(this.headers))); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java index b523414ad50..aa231e3b87a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java @@ -30,6 +30,7 @@ import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -71,10 +72,11 @@ public class DestinationVariableMethodArgumentResolverTests { assertEquals("value", result); } - @Test(expected = MessageHandlingException.class) + @Test public void resolveArgumentNotFound() { Message message = MessageBuilder.withPayload(new byte[0]).build(); - resolveArgument(this.resolvable.annot(destinationVar().noValue()).arg(), message); + assertThatExceptionOfType(MessageHandlingException.class).isThrownBy(() -> + resolveArgument(this.resolvable.annot(destinationVar().noValue()).arg(), message)); } @SuppressWarnings({"unchecked", "ConstantConditions"}) diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java index 0c03b5978f3..efc06f2378a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java @@ -34,6 +34,7 @@ import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -94,10 +95,11 @@ public class HeaderMethodArgumentResolverTests { this.resolvable.annot(header("nativeHeaders.param1")).arg(), message)); } - @Test(expected = MessageHandlingException.class) + @Test public void resolveArgumentNotFound() { Message message = MessageBuilder.withPayload(new byte[0]).build(); - resolveArgument(this.resolvable.annot(headerPlain()).arg(), message); + assertThatExceptionOfType(MessageHandlingException.class).isThrownBy(() -> + resolveArgument(this.resolvable.annot(headerPlain()).arg(), message)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java index 93c0c791f37..0c8ad4d2513 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java @@ -31,6 +31,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -70,9 +71,10 @@ public class HeadersMethodArgumentResolverTests { assertEquals("bar", headers.get("foo")); } - @Test(expected = IllegalStateException.class) + @Test public void resolveArgumentAnnotatedNotMap() { - resolveArgument(this.resolvable.annotPresent(Headers.class).arg(String.class)); + assertThatIllegalStateException().isThrownBy(() -> + resolveArgument(this.resolvable.annotPresent(Headers.class).arg(String.class))); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java index 6ad44eb6497..42003a37124 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java @@ -27,6 +27,7 @@ import org.springframework.messaging.handler.annotation.MessageExceptionHandler; import org.springframework.stereotype.Controller; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -93,14 +94,16 @@ public class AnnotationExceptionHandlerMethodResolverTests { assertEquals("handleIOException", this.resolver.resolveMethod(exception).getName()); } - @Test(expected = IllegalStateException.class) + @Test public void ambiguousExceptionMapping() { - new AnnotationExceptionHandlerMethodResolver(AmbiguousController.class); + assertThatIllegalStateException().isThrownBy(() -> + new AnnotationExceptionHandlerMethodResolver(AmbiguousController.class)); } - @Test(expected = IllegalStateException.class) + @Test public void noExceptionMapping() { - new AnnotationExceptionHandlerMethodResolver(NoExceptionController.class); + assertThatIllegalStateException().isThrownBy(() -> + new AnnotationExceptionHandlerMethodResolver(NoExceptionController.class)); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java index 90ac9b50b46..28d75b9c05d 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java @@ -29,6 +29,7 @@ import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -73,10 +74,11 @@ public class DestinationVariableMethodArgumentResolverTests { assertEquals("value", result); } - @Test(expected = MessageHandlingException.class) + @Test public void resolveArgumentNotFound() throws Exception { Message message = MessageBuilder.withPayload(new byte[0]).build(); - this.resolver.resolveArgument(this.resolvable.annot(destinationVar().noValue()).arg(), message); + assertThatExceptionOfType(MessageHandlingException.class).isThrownBy(() -> + this.resolver.resolveArgument(this.resolvable.annot(destinationVar().noValue()).arg(), message)); } @SuppressWarnings("unused") diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java index 0e09def4a48..fcad7d4ff20 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java @@ -33,6 +33,7 @@ import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -96,10 +97,11 @@ public class HeaderMethodArgumentResolverTests { this.resolvable.annot(header("nativeHeaders.param1")).arg(), message)); } - @Test(expected = MessageHandlingException.class) + @Test public void resolveArgumentNotFound() throws Exception { Message message = MessageBuilder.withPayload(new byte[0]).build(); - this.resolver.resolveArgument(this.resolvable.annot(headerPlain()).arg(), message); + assertThatExceptionOfType(MessageHandlingException.class).isThrownBy(() -> + this.resolver.resolveArgument(this.resolvable.annot(headerPlain()).arg(), message)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java index 20f07bbb676..0bb45346260 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java @@ -30,6 +30,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -74,9 +75,10 @@ public class HeadersMethodArgumentResolverTests { assertEquals("bar", headers.get("foo")); } - @Test(expected = IllegalStateException.class) + @Test public void resolveArgumentAnnotatedNotMap() throws Exception { - this.resolver.resolveArgument(this.resolvable.annotPresent(Headers.class).arg(String.class), this.message); + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.resolveArgument(this.resolvable.annotPresent(Headers.class).arg(String.class), this.message)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java index 962f1528af1..d666f1f717e 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java @@ -24,13 +24,11 @@ import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -73,15 +71,10 @@ public class InvocableHandlerMethodTests { @Test public void cannotResolveArg() throws Exception { - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); - invoke(new Handler(), method); - fail("Expected exception"); - } - catch (MethodArgumentResolutionException ex) { - assertNotNull(ex.getMessage()); - assertTrue(ex.getMessage().contains("Could not resolve parameter [0]")); - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); + assertThatExceptionOfType(MethodArgumentResolutionException.class).isThrownBy(() -> + invoke(new Handler(), method)) + .withMessageContaining("Could not resolve parameter [0]"); } @Test @@ -107,88 +100,57 @@ public class InvocableHandlerMethodTests { @Test public void exceptionInResolvingArg() throws Exception { this.resolvers.addResolver(new ExceptionRaisingArgumentResolver()); - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); - invoke(new Handler(), method); - fail("Expected exception"); - } - catch (IllegalArgumentException ex) { - // expected - allow HandlerMethodArgumentResolver exceptions to propagate - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); + assertThatIllegalArgumentException().isThrownBy(() -> + invoke(new Handler(), method)); + // expected - allow HandlerMethodArgumentResolver exceptions to propagate } @Test public void illegalArgumentException() throws Exception { this.resolvers.addResolver(new StubArgumentResolver(Integer.class, "__not_an_int__")); this.resolvers.addResolver(new StubArgumentResolver("value")); - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); - invoke(new Handler(), method); - fail("Expected exception"); - } - catch (IllegalStateException ex) { - assertNotNull("Exception not wrapped", ex.getCause()); - assertTrue(ex.getCause() instanceof IllegalArgumentException); - assertTrue(ex.getMessage().contains("Endpoint [")); - assertTrue(ex.getMessage().contains("Method [")); - assertTrue(ex.getMessage().contains("with argument values:")); - assertTrue(ex.getMessage().contains("[0] [type=java.lang.String] [value=__not_an_int__]")); - assertTrue(ex.getMessage().contains("[1] [type=java.lang.String] [value=value")); - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); + assertThatIllegalStateException().isThrownBy(() -> + invoke(new Handler(), method)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Endpoint [") + .withMessageContaining("Method [") + .withMessageContaining("with argument values:") + .withMessageContaining("[0] [type=java.lang.String] [value=__not_an_int__]") + .withMessageContaining("[1] [type=java.lang.String] [value=value"); } @Test public void invocationTargetException() throws Exception { Handler handler = new Handler(); Method method = ResolvableMethod.on(Handler.class).argTypes(Throwable.class).resolveMethod(); - Throwable expected = null; - try { - expected = new RuntimeException("error"); - invoke(handler, method, expected); - fail("Expected exception"); - } - catch (RuntimeException actual) { - assertSame(expected, actual); - } - try { - expected = new Error("error"); - invoke(handler, method, expected); - fail("Expected exception"); - } - catch (Error actual) { - assertSame(expected, actual); - } - try { - expected = new Exception("error"); - invoke(handler, method, expected); - fail("Expected exception"); - } - catch (Exception actual) { - assertSame(expected, actual); - } - try { - expected = new Throwable("error", expected); - invoke(handler, method, expected); - fail("Expected exception"); - } - catch (IllegalStateException actual) { - assertNotNull(actual.getCause()); - assertSame(expected, actual.getCause()); - assertTrue(actual.getMessage().contains("Invocation failure")); - } + RuntimeException runtimeException = new RuntimeException("error"); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + invoke(handler, method, runtimeException)) + .isSameAs(runtimeException); + Error error = new Error("error"); + assertThatExceptionOfType(Error.class).isThrownBy(() -> + invoke(handler, method, error)) + .isSameAs(error); + Exception exception = new Exception("error"); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + invoke(handler, method, exception)) + .isSameAs(exception); + Throwable throwable = new Throwable("error", exception); + assertThatIllegalStateException().isThrownBy(() -> + invoke(handler, method, throwable)) + .withCause(throwable) + .withMessageContaining("Invocation failure"); } @Test // Based on SPR-13917 (spring-web) public void invocationErrorMessage() throws Exception { this.resolvers.addResolver(new StubArgumentResolver(double.class)); - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0.0)).method(); - invoke(new Handler(), method); - fail(); - } - catch (IllegalStateException ex) { - assertThat(ex.getMessage(), containsString("Illegal argument")); - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0.0)).method(); + assertThatIllegalStateException().isThrownBy(() -> + invoke(new Handler(), method)) + .withMessageContaining("Illegal argument"); } @Nullable 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 c797e908a05..4ec4080e0a8 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 @@ -41,6 +41,7 @@ import org.springframework.util.AntPathMatcher; import org.springframework.util.Assert; import org.springframework.util.PathMatcher; +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; @@ -75,9 +76,10 @@ public class MethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); } - @Test(expected = IllegalStateException.class) + @Test public void duplicateMapping() { - this.messageHandler.registerHandler(new DuplicateMappingsController()); + assertThatIllegalStateException().isThrownBy(() -> + this.messageHandler.registerHandler(new DuplicateMappingsController())); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java index 16442c086f2..b4833cee56d 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java @@ -32,12 +32,13 @@ import org.springframework.messaging.Message; import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException; import org.springframework.messaging.handler.invocation.ResolvableMethod; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -81,15 +82,10 @@ public class InvocableHandlerMethodTests { @Test public void cannotResolveArg() { - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); - invokeAndBlock(new Handler(), method); - fail("Expected exception"); - } - catch (MethodArgumentResolutionException ex) { - assertNotNull(ex.getMessage()); - assertTrue(ex.getMessage().contains("Could not resolve parameter [0]")); - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); + assertThatExceptionOfType(MethodArgumentResolutionException.class).isThrownBy(() -> + invokeAndBlock(new Handler(), method)) + .withMessageContaining("Could not resolve parameter [0]"); } @Test @@ -115,34 +111,24 @@ public class InvocableHandlerMethodTests { @Test public void exceptionInResolvingArg() { this.resolvers.add(new InvocableHandlerMethodTests.ExceptionRaisingArgumentResolver()); - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); - invokeAndBlock(new Handler(), method); - fail("Expected exception"); - } - catch (IllegalArgumentException ex) { - // expected - allow HandlerMethodArgumentResolver exceptions to propagate - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); + assertThatIllegalArgumentException().isThrownBy(() -> + invokeAndBlock(new Handler(), method)); } @Test public void illegalArgumentException() { this.resolvers.add(new StubArgumentResolver(Integer.class, "__not_an_int__")); this.resolvers.add(new StubArgumentResolver("value")); - try { - Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); - invokeAndBlock(new Handler(), method); - fail("Expected exception"); - } - catch (IllegalStateException ex) { - assertNotNull("Exception not wrapped", ex.getCause()); - assertTrue(ex.getCause() instanceof IllegalArgumentException); - assertTrue(ex.getMessage().contains("Endpoint [")); - assertTrue(ex.getMessage().contains("Method [")); - assertTrue(ex.getMessage().contains("with argument values:")); - assertTrue(ex.getMessage().contains("[0] [type=java.lang.String] [value=__not_an_int__]")); - assertTrue(ex.getMessage().contains("[1] [type=java.lang.String] [value=value")); - } + Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); + assertThatIllegalStateException().isThrownBy(() -> + invokeAndBlock(new Handler(), method)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Endpoint [") + .withMessageContaining("Method [") + .withMessageContaining("with argument values:") + .withMessageContaining("[0] [type=java.lang.String] [value=__not_an_int__]") + .withMessageContaining("[1] [type=java.lang.String] [value=value"); } @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 86a6b6fb805..5d796b24928 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 @@ -47,6 +47,7 @@ import org.springframework.util.PathMatcher; import org.springframework.util.RouteMatcher; import org.springframework.util.SimpleRouteMatcher; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @@ -57,9 +58,10 @@ import static org.junit.Assert.assertEquals; public class MethodMessageHandlerTests { - @Test(expected = IllegalStateException.class) + @Test public void duplicateMapping() { - initMethodMessageHandler(DuplicateMappingsController.class); + assertThatIllegalStateException().isThrownBy(() -> + initMethodMessageHandler(DuplicateMappingsController.class)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java index 80fa1e8f91b..00872d7cdc0 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java @@ -44,11 +44,11 @@ import org.springframework.messaging.rsocket.RSocketRequester.ResponseSpec; import org.springframework.util.MimeTypeUtils; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link DefaultRSocketRequester}. @@ -194,13 +194,9 @@ public class DefaultRSocketRequesterTests { @Test public void rejectFluxToMono() { - try { - this.requester.route("").data(Flux.just("a", "b")).retrieveMono(String.class); - fail(); - } - catch (IllegalArgumentException ex) { - assertEquals("No RSocket interaction model for Flux request to Mono response.", ex.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.requester.route("").data(Flux.just("a", "b")).retrieveMono(String.class)) + .withMessage("No RSocket interaction model for Flux request to Mono response."); } private Payload toPayload(String value) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java index c930f608e32..8924b8a0293 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java @@ -38,6 +38,7 @@ import org.springframework.messaging.simp.TestPrincipal; import org.springframework.messaging.support.MessageBuilder; import org.springframework.scheduling.TaskScheduler; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -176,10 +177,11 @@ public class SimpleBrokerMessageHandlerTests { assertArrayEquals(new long[] {10000, 10000}, this.messageHandler.getHeartbeatValue()); } - @Test(expected = IllegalArgumentException.class) + @Test public void startWithHeartbeatValueWithoutTaskScheduler() { this.messageHandler.setHeartbeatValue(new long[] {10000, 10000}); - this.messageHandler.start(); + assertThatIllegalArgumentException().isThrownBy( + this.messageHandler::start); } @SuppressWarnings("unchecked") diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java index e9ce34bf87e..873ce160003 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java @@ -25,9 +25,9 @@ import org.junit.Test; import org.springframework.messaging.Message; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * Unit tests for {@link BufferingStompDecoder}. @@ -153,21 +153,17 @@ public class BufferingStompDecoderTests { assertEquals(24, stompDecoder.getBufferSize()); assertEquals(129, (int) stompDecoder.getExpectedContentLength()); - try { - String chunk2 = "\nPayload2a"; - stompDecoder.decode(toByteBuffer(chunk2)); - fail("Expected exception"); - } - catch (StompConversionException ex) { - // expected - } + String chunk2 = "\nPayload2a"; + assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> + stompDecoder.decode(toByteBuffer(chunk2))); } - @Test(expected = StompConversionException.class) + @Test public void bufferSizeLimit() { BufferingStompDecoder stompDecoder = new BufferingStompDecoder(STOMP_DECODER, 10); String payload = "SEND\na:alpha\n\nMessage body"; - stompDecoder.decode(toByteBuffer(payload)); + assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> + stompDecoder.decode(toByteBuffer(payload))); } @Test @@ -190,18 +186,20 @@ public class BufferingStompDecoderTests { assertEquals(0, messages.size()); } - @Test(expected = StompConversionException.class) + @Test public void invalidEscapeSequence() { BufferingStompDecoder stompDecoder = new BufferingStompDecoder(STOMP_DECODER, 128); String payload = "SEND\na:alpha\\x\\n\nMessage body\0"; - stompDecoder.decode(toByteBuffer(payload)); + assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> + stompDecoder.decode(toByteBuffer(payload))); } - @Test(expected = StompConversionException.class) + @Test public void invalidEscapeSequenceWithSingleSlashAtEndOfHeaderValue() { BufferingStompDecoder stompDecoder = new BufferingStompDecoder(STOMP_DECODER, 128); String payload = "SEND\na:alpha\\\n\nMessage body\0"; - stompDecoder.decode(toByteBuffer(payload)); + assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> + stompDecoder.decode(toByteBuffer(payload))); } private ByteBuffer toByteBuffer(String chunk) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java index bde6b441a0f..ca4085bfeec 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java @@ -49,6 +49,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -168,7 +169,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { this.responseHandler.expectMessages(send); } - @Test(expected = MessageDeliveryException.class) + @Test public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Exception { logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()"); @@ -176,7 +177,8 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { this.eventPublisher.expectBrokerAvailabilityEvent(false); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND); - this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders())); + assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> + this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders()))); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java index ab8bd2cb84c..ca6018f947d 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java @@ -18,11 +18,11 @@ package org.springframework.messaging.simp.stomp; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link StompClientSupport}. @@ -41,13 +41,8 @@ public class StompClientSupportTests { } private void trySetDefaultHeartbeat(long[] heartbeat) { - try { - this.stompClient.setDefaultHeartbeat(heartbeat); - fail("Expected exception"); - } - catch (IllegalArgumentException ex) { - // Ignore - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.stompClient.setDefaultHeartbeat(heartbeat)); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java index fcfc9b3419d..b7c92868fc7 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java @@ -26,6 +26,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.util.InvalidMimeTypeException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -160,9 +161,10 @@ public class StompDecoderTests { assertEquals("alpha:bravo\r\n\\", headers.getFirstNativeHeader("a:\r\n\\b")); } - @Test(expected = StompConversionException.class) + @Test public void decodeFrameBodyNotAllowed() { - decode("CONNECT\naccept-version:1.2\n\nThe body of the message\0"); + assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> + decode("CONNECT\naccept-version:1.2\n\nThe body of the message\0")); } @Test @@ -226,14 +228,16 @@ public class StompDecoderTests { assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U"); } - @Test(expected = InvalidMimeTypeException.class) + @Test public void decodeFrameWithInvalidContentType() { - assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U\n\nThe body\0"); + assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() -> + assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U\n\nThe body\0")); } - @Test(expected = StompConversionException.class) + @Test public void decodeFrameWithIncorrectTerminator() { - decode("SEND\ncontent-length:23\n\nThe body of the message*"); + assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> + decode("SEND\ncontent-length:23\n\nThe body of the message*")); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java index 7eb06918425..86877179532 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java @@ -27,6 +27,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.util.IdGenerator; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -75,16 +76,18 @@ public class MessageBuilderTests { assertEquals("2", message2.getHeaders().get("bar")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIdHeaderValueReadOnly() { UUID id = UUID.randomUUID(); - MessageBuilder.withPayload("test").setHeader(MessageHeaders.ID, id); + assertThatIllegalArgumentException().isThrownBy(() -> + MessageBuilder.withPayload("test").setHeader(MessageHeaders.ID, id)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testTimestampValueReadOnly() { Long timestamp = 12345L; - MessageBuilder.withPayload("test").setHeader(MessageHeaders.TIMESTAMP, timestamp).build(); + assertThatIllegalArgumentException().isThrownBy(() -> + MessageBuilder.withPayload("test").setHeader(MessageHeaders.TIMESTAMP, timestamp).build()); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java index 0e53a68e6c3..213a82db9b6 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java @@ -29,12 +29,12 @@ import org.springframework.orm.jpa.domain.DriversLicense; import org.springframework.orm.jpa.domain.Person; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Integration tests for LocalContainerEntityManagerFactoryBean. @@ -95,30 +95,22 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests @Test public void testBogusQuery() { - try { + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { Query query = sharedEntityManager.createQuery("It's raining toads"); // required in OpenJPA case query.executeUpdate(); - fail("Should have thrown a RuntimeException"); - } - catch (RuntimeException ex) { - // expected - } + }); } @Test public void testGetReferenceWhenNoRow() { - try { - Person notThere = sharedEntityManager.getReference(Person.class, 666); - - // We may get here (as with Hibernate). Either behaviour is valid: - // throw exception on first access or on getReference itself. - notThere.getFirstName(); - fail("Should have thrown an EntityNotFoundException or ObjectNotFoundException"); - } - catch (Exception ex) { - assertTrue(ex.getClass().getName().endsWith("NotFoundException")); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> { + Person notThere = sharedEntityManager.getReference(Person.class, 666); + // We may get here (as with Hibernate). Either behaviour is valid: + // throw exception on first access or on getReference itself. + notThere.getFirstName(); + }) + .matches(ex -> ex.getClass().getName().endsWith("NotFoundException")); } @Test @@ -169,12 +161,8 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests @Test public void testEntityManagerProxyRejectsProgrammaticTxManagement() { - try { - sharedEntityManager.getTransaction(); - fail("Should not be able to create transactions on container managed EntityManager"); - } - catch (IllegalStateException ex) { - } + assertThatIllegalStateException().as("Should not be able to create transactions on container managed EntityManager").isThrownBy( + sharedEntityManager::getTransaction); } @Test @@ -200,13 +188,8 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); assertEquals(0, people.size()); - try { - assertNull(q.getSingleResult()); - fail("Should have thrown NoResultException"); - } - catch (NoResultException ex) { - // expected - } + assertThatExceptionOfType(NoResultException.class).isThrownBy( + q::getSingleResult); } @Test @@ -218,13 +201,8 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); assertEquals(0, people.size()); - try { - assertNull(q.getSingleResult()); - fail("Should have thrown NoResultException"); - } - catch (NoResultException ex) { - // expected - } + assertThatExceptionOfType(NoResultException.class).isThrownBy( + q::getSingleResult); } @Test @@ -234,13 +212,8 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests q.setFlushMode(FlushModeType.AUTO); List people = q.getResultList(); assertEquals(0, people.size()); - try { - assertNull(q.getSingleResult()); - fail("Should have thrown NoResultException"); - } - catch (NoResultException ex) { - // expected - } + assertThatExceptionOfType(NoResultException.class).isThrownBy( + q::getSingleResult); } @Test @@ -253,24 +226,16 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests q.setFlushMode(FlushModeType.AUTO); List people = q.getResultList(); assertEquals(0, people.size()); - try { - assertNull(q.getSingleResult()); - fail("Should have thrown IllegalStateException"); - } - catch (Exception ex) { - // We would typically expect an IllegalStateException, but Hibernate throws a - // PersistenceException. So we assert the contents of the exception message instead. - assertTrue(ex.getMessage().contains("closed")); - } - q = em.createQuery("select p from Person as p"); - q.setFlushMode(FlushModeType.AUTO); - try { - assertNull(q.getSingleResult()); - fail("Should have thrown NoResultException"); - } - catch (NoResultException ex) { - // expected - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + q.getSingleResult()) + .withMessageContaining("closed"); + // We would typically expect an IllegalStateException, but Hibernate throws a + // PersistenceException. So we assert the contents of the exception message instead. + + Query q2 = em.createQuery("select p from Person as p"); + q2.setFlushMode(FlushModeType.AUTO); + assertThatExceptionOfType(NoResultException.class).isThrownBy( + q2::getSingleResult); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java index baf65d8a429..280acb0eac8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java @@ -26,11 +26,11 @@ import org.junit.Test; import org.springframework.orm.jpa.domain.Person; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * An application-managed entity manager can join an existing transaction, @@ -72,13 +72,8 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt @Test public void testCannotFlushWithoutGettingTransaction() { EntityManager em = entityManagerFactory.createEntityManager(); - try { - doInstantiateAndSave(em); - fail("Should have thrown TransactionRequiredException"); - } - catch (TransactionRequiredException ex) { - // expected - } + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy(() -> + doInstantiateAndSave(em)); // TODO following lines are a workaround for Hibernate bug // If Hibernate throws an exception due to flush(), diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java index 8afda49c786..14353877fcc 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java @@ -30,13 +30,14 @@ import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.orm.jpa.domain.Person; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Integration tests using in-memory database for container-managed JPA @@ -81,26 +82,16 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit assertTrue(people.isEmpty()); assertTrue("Should be open to start with", em.isOpen()); - try { - em.close(); - fail("Close should not work on container managed EM"); - } - catch (IllegalStateException ex) { - // OK - } + assertThatIllegalStateException().as("Close should not work on container managed EM").isThrownBy( + em::close); assertTrue(em.isOpen()); } // This would be legal, at least if not actually _starting_ a tx @Test public void testEntityManagerProxyRejectsProgrammaticTxManagement() { - try { - createContainerManagedEntityManager().getTransaction(); - fail("Should have thrown an IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy( + createContainerManagedEntityManager()::getTransaction); } /* @@ -115,14 +106,8 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit @Test public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() { endTransaction(); - - try { - createContainerManagedEntityManager().joinTransaction(); - fail("Should have thrown a TransactionRequiredException"); - } - catch (TransactionRequiredException ex) { - // expected - } + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy( + createContainerManagedEntityManager()::joinTransaction); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java index c785eedb877..9222f4cd368 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java @@ -26,8 +26,8 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.DefaultTransactionDefinition; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -43,14 +43,8 @@ public class DefaultJpaDialectTests { public void testDefaultTransactionDefinition() throws Exception { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - - try { - dialect.beginTransaction(null, definition); - fail("expected exception"); - } - catch (TransactionException e) { - // ok - } + assertThatExceptionOfType(TransactionException.class).isThrownBy(() -> + dialect.beginTransaction(null, definition)); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java index 86a0c4893ac..201e7d697ec 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java @@ -35,10 +35,10 @@ import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -57,13 +57,8 @@ public class EntityManagerFactoryUtilsTests { @Test public void testDoGetEntityManager() { // test null assertion - try { - EntityManagerFactoryUtils.doGetTransactionalEntityManager(null, null); - fail("expected exception"); - } - catch (IllegalArgumentException ex) { - // it's okay - } + assertThatIllegalArgumentException().isThrownBy(() -> + EntityManagerFactoryUtils.doGetTransactionalEntityManager(null, null)); EntityManagerFactory factory = mock(EntityManagerFactory.class); // no tx active diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java index b7112661838..2cfae41b798 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java @@ -37,11 +37,10 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -164,7 +163,7 @@ public class JpaTransactionManagerTests { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -172,13 +171,7 @@ public class JpaTransactionManagerTests { EntityManagerFactoryUtils.getTransactionalEntityManager(factory); throw new RuntimeException("some exception"); } - }); - fail("Should have propagated RuntimeException"); - } - catch (RuntimeException ex) { - // expected - assertEquals("some exception", ex.getMessage()); - } + })).withMessage("some exception"); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -197,7 +190,7 @@ public class JpaTransactionManagerTests { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -205,12 +198,7 @@ public class JpaTransactionManagerTests { EntityManagerFactoryUtils.getTransactionalEntityManager(factory); throw new RuntimeException("some exception"); } - }); - fail("Should have propagated RuntimeException"); - } - catch (RuntimeException ex) { - // expected - } + })); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -293,7 +281,7 @@ public class JpaTransactionManagerTests { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -306,12 +294,7 @@ public class JpaTransactionManagerTests { } }); } - }); - fail("Should have propagated RuntimeException"); - } - catch (RuntimeException ex) { - // expected - } + })); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -334,28 +317,23 @@ public class JpaTransactionManagerTests { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - try { - tt.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> + tt.execute(new TransactionCallback() { + @Override + public Object doInTransaction(TransactionStatus status) { + assertTrue(TransactionSynchronizationManager.hasResource(factory)); - return tt.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); - status.setRollbackOnly(); - return null; - } - }); - } - }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException tse) { - // expected - assertTrue(tse.getCause() instanceof RollbackException); - } + return tt.execute(new TransactionCallback() { + @Override + public Object doInTransaction(TransactionStatus status) { + EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); + status.setRollbackOnly(); + return null; + } + }); + } + })) + .withCauseInstanceOf(RollbackException.class); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -770,17 +748,12 @@ public class JpaTransactionManagerTests { given(manager.isOpen()).willReturn(true); - try { + assertThatExceptionOfType(InvalidIsolationLevelException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { } - }); - fail("Should have thrown InvalidIsolationLevelException"); - } - catch (InvalidIsolationLevelException ex) { - // expected - } + })); verify(manager).close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java index d78f79c7644..995c8cd3980 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java @@ -39,6 +39,8 @@ import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.interceptor.DefaultTransactionAttribute; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -46,7 +48,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -196,13 +197,8 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM em.joinTransaction(); assertFalse(em.contains(testEntity)); - try { - jpatm.commit(txStatus); - fail("Should have thrown OptimisticLockingFailureException"); - } - catch (OptimisticLockingFailureException ex) { - // expected - } + assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> + jpatm.commit(txStatus)); cefb.destroy(); @@ -259,13 +255,8 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM @Test public void testInvalidPersistenceUnitName() throws Exception { - try { - createEntityManagerFactoryBean("org/springframework/orm/jpa/domain/persistence.xml", null, "call me Bob"); - fail("Should not create factory with this name"); - } - catch (IllegalArgumentException ex) { - // Ok - } + assertThatIllegalArgumentException().isThrownBy(() -> + createEntityManagerFactoryBean("org/springframework/orm/jpa/domain/persistence.xml", null, "call me Bob")); } protected LocalContainerEntityManagerFactoryBean createEntityManagerFactoryBean( @@ -306,13 +297,8 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM containerEmfb.setPersistenceUnitName(entityManagerName); containerEmfb.setPersistenceProviderClass(DummyContainerPersistenceProvider.class); - try { - containerEmfb.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException ex) { - // Ok - } + assertThatIllegalArgumentException().isThrownBy( + containerEmfb::afterPropertiesSet); } 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 c721a71c094..88097bfa0bc 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,12 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; +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.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; @@ -56,46 +57,52 @@ public class SharedEntityManagerCreatorTests { assertThat(SharedEntityManagerCreator.createSharedEntityManager(emf), is(notNullValue())); } - @Test(expected = TransactionRequiredException.class) + @Test public void transactionRequiredExceptionOnJoinTransaction() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); - em.joinTransaction(); + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy( + em::joinTransaction); } - @Test(expected = TransactionRequiredException.class) + @Test public void transactionRequiredExceptionOnFlush() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); - em.flush(); + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy( + em::flush); } - @Test(expected = TransactionRequiredException.class) + @Test public void transactionRequiredExceptionOnPersist() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); - em.persist(new Object()); + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy(() -> + em.persist(new Object())); } - @Test(expected = TransactionRequiredException.class) + @Test public void transactionRequiredExceptionOnMerge() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); - em.merge(new Object()); + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy(() -> + em.merge(new Object())); } - @Test(expected = TransactionRequiredException.class) + @Test public void transactionRequiredExceptionOnRemove() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); - em.remove(new Object()); + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy(() -> + em.remove(new Object())); } - @Test(expected = TransactionRequiredException.class) + @Test public void transactionRequiredExceptionOnRefresh() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); - em.refresh(new Object()); + assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy(() -> + em.refresh(new Object())); } @Test @@ -180,13 +187,8 @@ public class SharedEntityManagerCreatorTests { spq.registerStoredProcedureParameter(2, Object.class, ParameterMode.INOUT); spq.execute(); assertEquals("y", spq.getOutputParameterValue(0)); - try { - spq.getOutputParameterValue(1); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + spq.getOutputParameterValue(1)); assertEquals("z", spq.getOutputParameterValue(2)); verify(query).registerStoredProcedureParameter(0, String.class, ParameterMode.OUT); @@ -216,13 +218,8 @@ public class SharedEntityManagerCreatorTests { spq.registerStoredProcedureParameter("c", Object.class, ParameterMode.INOUT); spq.execute(); assertEquals("y", spq.getOutputParameterValue("a")); - try { - spq.getOutputParameterValue("b"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + spq.getOutputParameterValue("b")); assertEquals("z", spq.getOutputParameterValue("c")); verify(query).registerStoredProcedureParameter("a", String.class, ParameterMode.OUT); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java index 3cd2ef3d20c..9ba162e021f 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java @@ -25,10 +25,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests; import org.springframework.orm.jpa.EntityManagerFactoryInfo; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Hibernate-specific JPA tests with multiple EntityManagerFactory instances. @@ -61,11 +61,8 @@ public class HibernateMultiEntityManagerFactoryIntegrationTests extends Abstract public void testEntityManagerFactory2() { EntityManager em = this.entityManagerFactory2.createEntityManager(); try { - em.createQuery("select tb from TestBean"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected + assertThatIllegalArgumentException().isThrownBy(() -> + em.createQuery("select tb from TestBean")); } finally { em.close(); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java index 80b370a302d..1c0a5099ad3 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java @@ -35,6 +35,7 @@ import org.springframework.orm.jpa.hibernate.beans.MultiplePrototypesInSpringCon import org.springframework.orm.jpa.hibernate.beans.NoDefinitionInSpringContextTestBean; import org.springframework.orm.jpa.hibernate.beans.SinglePrototypeInSpringContextTestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; @@ -246,32 +247,36 @@ public class HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTe assertNull(instance.getApplicationContext()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testFallbackExceptionInCaseOfNoSpringBeanFound() { - getBeanContainer().getBean(NoDefinitionInSpringContextTestBean.class, - NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE - ); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + getBeanContainer().getBean(NoDefinitionInSpringContextTestBean.class, + NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE + )); } - @Test(expected = BeanCreationException.class) + @Test public void testOriginalExceptionInCaseOfFallbackProducerFailure() { - getBeanContainer().getBean(AttributeConverter.class, - NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE - ); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + getBeanContainer().getBean(AttributeConverter.class, + NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE + )); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testFallbackExceptionInCaseOfNoSpringBeanFoundByName() { - getBeanContainer().getBean("some name", NoDefinitionInSpringContextTestBean.class, - NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE - ); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + getBeanContainer().getBean("some name", NoDefinitionInSpringContextTestBean.class, + NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE + )); } - @Test(expected = BeanCreationException.class) + @Test public void testOriginalExceptionInCaseOfFallbackProducerFailureByName() { - getBeanContainer().getBean("invalid", AttributeConverter.class, - NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE - ); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + getBeanContainer().getBean("invalid", AttributeConverter.class, + NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE + )); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java index dca1a1ed1fe..f2e16a0b662 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java @@ -36,13 +36,13 @@ import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup; import org.springframework.jdbc.datasource.lookup.MapDataSourceLookup; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit and integration tests for the JPA XML resource parsing support. @@ -264,12 +264,8 @@ public class PersistenceXmlParsingTests { PersistenceUnitReader reader = new PersistenceUnitReader( new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup()); String resource = "/org/springframework/orm/jpa/persistence-invalid.xml"; - try { - reader.readPersistenceUnitInfos(resource); - fail("expected invalid document exception"); - } - catch (RuntimeException expected) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + reader.readPersistenceUnitInfos(resource)); } @Ignore // not doing schema parsing anymore for JPA 2.0 compatibility @@ -278,12 +274,8 @@ public class PersistenceXmlParsingTests { PersistenceUnitReader reader = new PersistenceUnitReader( new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup()); String resource = "/org/springframework/orm/jpa/persistence-no-schema.xml"; - try { - reader.readPersistenceUnitInfos(resource); - fail("expected invalid document exception"); - } - catch (RuntimeException expected) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + reader.readPersistenceUnitInfos(resource)); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java index ee9f6f8cd3d..f1e036f314e 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java @@ -48,10 +48,10 @@ import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -551,37 +551,22 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT @Test public void testFieldOfWrongTypeAnnotatedWithPersistenceUnit() { PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor(); - try { - pabpp.postProcessProperties(null, new FieldOfWrongTypeAnnotatedWithPersistenceUnit(), "bean"); - fail("Can't inject this field"); - } - catch (IllegalStateException ex) { - // Ok - } + assertThatIllegalStateException().isThrownBy(() -> + pabpp.postProcessProperties(null, new FieldOfWrongTypeAnnotatedWithPersistenceUnit(), "bean")); } @Test public void testSetterOfWrongTypeAnnotatedWithPersistenceUnit() { PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor(); - try { - pabpp.postProcessProperties(null, new SetterOfWrongTypeAnnotatedWithPersistenceUnit(), "bean"); - fail("Can't inject this setter"); - } - catch (IllegalStateException ex) { - // Ok - } + assertThatIllegalStateException().isThrownBy(() -> + pabpp.postProcessProperties(null, new SetterOfWrongTypeAnnotatedWithPersistenceUnit(), "bean")); } @Test public void testSetterWithNoArgs() { PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor(); - try { - pabpp.postProcessProperties(null, new SetterWithNoArgs(), "bean"); - fail("Can't inject this setter"); - } - catch (IllegalStateException ex) { - // Ok - } + assertThatIllegalStateException().isThrownBy(() -> + pabpp.postProcessProperties(null, new SetterWithNoArgs(), "bean")); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java index 20f0da79a2b..3ecca6d8079 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java @@ -25,10 +25,10 @@ import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.orm.jpa.EntityManagerProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -63,13 +63,8 @@ public class SharedEntityManagerFactoryTests { assertTrue(proxy instanceof EntityManagerProxy); EntityManagerProxy emProxy = (EntityManagerProxy) proxy; - try { - emProxy.getTargetEntityManager(); - fail("Should have thrown IllegalStateException outside of transaction"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().as("outside of transaction").isThrownBy( + emProxy::getTargetEntityManager); TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(mockEm)); try { 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 648ca6d8c33..95dea03b6ef 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 @@ -55,11 +55,12 @@ import org.springframework.oxm.mime.MimeContainer; import org.springframework.util.FileCopyUtils; import org.springframework.util.ReflectionUtils; +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; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -148,27 +149,30 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests + marshaller.marshal(flights, result)); } @Test @@ -238,7 +242,7 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests } - @Test(expected = IllegalArgumentException.class) + @Test public void afterPropertiesSetNoContextPath() throws Exception { JibxMarshaller marshaller = new JibxMarshaller(); - marshaller.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + marshaller::afterPropertiesSet); } @Test 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 6669a5430cf..8cbda1dd848 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,11 +28,11 @@ import javax.servlet.ServletResponse; import org.junit.Before; import org.junit.Test; +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.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -53,26 +53,30 @@ public class MockFilterChainTests { this.response = new MockHttpServletResponse(); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorNullServlet() { - new MockFilterChain((Servlet) null); + assertThatIllegalArgumentException().isThrownBy(() -> + new MockFilterChain((Servlet) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorNullFilter() { - new MockFilterChain(mock(Servlet.class), (Filter) null); + assertThatIllegalArgumentException().isThrownBy(() -> + new MockFilterChain(mock(Servlet.class), (Filter) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void doFilterNullRequest() throws Exception { MockFilterChain chain = new MockFilterChain(); - chain.doFilter(null, this.response); + assertThatIllegalArgumentException().isThrownBy(() -> + chain.doFilter(null, this.response)); } - @Test(expected = IllegalArgumentException.class) + @Test public void doFilterNullResponse() throws Exception { MockFilterChain chain = new MockFilterChain(); - chain.doFilter(this.request, null); + assertThatIllegalArgumentException().isThrownBy(() -> + chain.doFilter(this.request, null)); } @Test @@ -83,13 +87,9 @@ public class MockFilterChainTests { assertThat(chain.getRequest(), is(request)); assertThat(chain.getResponse(), is(response)); - try { - chain.doFilter(this.request, this.response); - fail("Expected Exception"); - } - catch (IllegalStateException ex) { - assertEquals("This FilterChain has already been called!", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + chain.doFilter(this.request, this.response)) + .withMessage("This FilterChain has already been called!"); } @Test @@ -98,13 +98,9 @@ public class MockFilterChainTests { MockFilterChain chain = new MockFilterChain(servlet); chain.doFilter(this.request, this.response); verify(servlet).service(this.request, this.response); - try { - chain.doFilter(this.request, this.response); - fail("Expected Exception"); - } - catch (IllegalStateException ex) { - assertEquals("This FilterChain has already been called!", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + chain.doFilter(this.request, this.response)) + .withMessage("This FilterChain has already been called!"); } @Test @@ -122,13 +118,9 @@ public class MockFilterChainTests { verify(servlet).service(this.request, this.response); - try { - chain.doFilter(this.request, this.response); - fail("Expected Exception"); - } - catch (IllegalStateException ex) { - assertEquals("This FilterChain has already been called!", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + chain.doFilter(this.request, this.response)) + .withMessage("This FilterChain has already been called!"); } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java index 14abd2b8723..6f5bc2fa634 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java @@ -35,6 +35,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -314,14 +315,16 @@ public class MockHttpServletRequestTests { } } - @Test(expected = IllegalArgumentException.class) + @Test public void setPreferredLocalesWithNullList() { - request.setPreferredLocales(null); + assertThatIllegalArgumentException().isThrownBy(() -> + request.setPreferredLocales(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setPreferredLocalesWithEmptyList() { - request.setPreferredLocales(new ArrayList<>()); + assertThatIllegalArgumentException().isThrownBy(() -> + request.setPreferredLocales(new ArrayList<>())); } @Test @@ -556,10 +559,11 @@ public class MockHttpServletRequestTests { assertEquals(1437472800000L, request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); } - @Test(expected = IllegalArgumentException.class) + @Test public void httpHeaderFormattedDateError() { request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, "This is not a date"); - request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); + assertThatIllegalArgumentException().isThrownBy(() -> + request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); } private void assertEqualEnumerations(Enumeration enum1, Enumeration enum2) { diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index d53dc6a9f8e..a27964246d9 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -298,11 +299,12 @@ public class MockHttpServletResponseTests { assertEquals(time, response.getDateHeader("Last-Modified")); } - @Test(expected = IllegalArgumentException.class) + @Test public void getInvalidDateHeader() { response.setHeader("Last-Modified", "invalid"); assertEquals("invalid", response.getHeader("Last-Modified")); - response.getDateHeader("Last-Modified"); + assertThatIllegalArgumentException().isThrownBy(() -> + response.getDateHeader("Last-Modified")); } @Test // SPR-16160 diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java index 6e5bb90c489..f2f00cd6dd3 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java @@ -22,6 +22,7 @@ import javax.servlet.http.HttpSessionBindingListener; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -45,109 +46,88 @@ public class MockHttpSessionTests { assertTrue(session.isInvalid()); } - @Test(expected = IllegalStateException.class) + @Test public void invalidateTwice() { session.invalidate(); - session.invalidate(); + assertThatIllegalStateException().isThrownBy( + session::invalidate); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void getCreationTimeOnInvalidatedSession() { session.invalidate(); - session.getCreationTime(); + assertThatIllegalStateException().isThrownBy( + session::getCreationTime); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void getLastAccessedTimeOnInvalidatedSession() { session.invalidate(); - session.getLastAccessedTime(); + assertThatIllegalStateException().isThrownBy( + session::getLastAccessedTime); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void getAttributeOnInvalidatedSession() { session.invalidate(); - session.getAttribute("foo"); + assertThatIllegalStateException().isThrownBy(() -> + session.getAttribute("foo")); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void getAttributeNamesOnInvalidatedSession() { session.invalidate(); - session.getAttributeNames(); + assertThatIllegalStateException().isThrownBy( + session::getAttributeNames); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void getValueOnInvalidatedSession() { session.invalidate(); - session.getValue("foo"); + assertThatIllegalStateException().isThrownBy(() -> + session.getValue("foo")); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void getValueNamesOnInvalidatedSession() { session.invalidate(); - session.getValueNames(); + assertThatIllegalStateException().isThrownBy( + session::getValueNames); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void setAttributeOnInvalidatedSession() { session.invalidate(); - session.setAttribute("name", "value"); + assertThatIllegalStateException().isThrownBy(() -> + session.setAttribute("name", "value")); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void putValueOnInvalidatedSession() { session.invalidate(); - session.putValue("name", "value"); + assertThatIllegalStateException().isThrownBy(() -> + session.putValue("name", "value")); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void removeAttributeOnInvalidatedSession() { session.invalidate(); - session.removeAttribute("name"); + assertThatIllegalStateException().isThrownBy(() -> + session.removeAttribute("name")); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void removeValueOnInvalidatedSession() { session.invalidate(); - session.removeValue("name"); + assertThatIllegalStateException().isThrownBy(() -> + session.removeValue("name")); } - /** - * @since 4.0 - */ - @Test(expected = IllegalStateException.class) + @Test public void isNewOnInvalidatedSession() { session.invalidate(); - session.isNew(); + assertThatIllegalStateException().isThrownBy( + session::isNew); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java b/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java index dc912521314..d2d35361688 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java @@ -20,6 +20,8 @@ import java.lang.reflect.Method; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -55,18 +57,17 @@ public class TestContextManagerSuppressedExceptionsTests { TestContextManager testContextManager = new TestContextManager(testClass); assertEquals("Registered TestExecutionListeners", 2, testContextManager.getTestExecutionListeners().size()); - try { - Method testMethod = getClass().getMethod("toString"); - callback.invoke(testContextManager, testClass, testMethod); - fail("should have thrown an AssertionError"); - } - catch (AssertionError err) { - // 'after' callbacks are reversed, so 2 comes before 1. - assertEquals(useCase + "-2", err.getMessage()); - Throwable[] suppressed = err.getSuppressed(); - assertEquals(1, suppressed.length); - assertEquals(useCase + "-1", suppressed[0].getMessage()); - } + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> { + Method testMethod = getClass().getMethod("toString"); + callback.invoke(testContextManager, testClass, testMethod); + fail("should have thrown an AssertionError"); + }).satisfies(ex -> { + // 'after' callbacks are reversed, so 2 comes before 1. + assertThat(ex.getMessage()).isEqualTo(useCase + "-2"); + Throwable[] suppressed = ex.getSuppressed(); + assertThat(suppressed).hasSize(1); + assertThat(suppressed[0].getMessage()).isEqualTo(useCase + "-1"); + }); } diff --git a/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java b/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java index e176555e5f6..50d73299d8a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java @@ -35,6 +35,7 @@ import org.springframework.test.context.web.ServletTestExecutionListener; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS; @@ -164,9 +165,10 @@ public class TestExecutionListenersTests { assertNumRegisteredListeners(MetaNonInheritedListenersWithOverridesTestCase.class, 8); } - @Test(expected = AnnotationConfigurationException.class) + @Test public void listenersAndValueAttributesDeclared() { - new TestContextManager(DuplicateListenersConfigTestCase.class); + assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() -> + new TestContextManager(DuplicateListenersConfigTestCase.class)); } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java index 00383e97e44..dc7ec0f3d42 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java @@ -28,6 +28,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -55,14 +56,16 @@ public class LruContextCacheTests { private final ConfigurableApplicationContext bazContext = mock(ConfigurableApplicationContext.class); - @Test(expected = IllegalArgumentException.class) + @Test public void maxCacheSizeNegativeOne() { - new DefaultContextCache(-1); + assertThatIllegalArgumentException().isThrownBy(() -> + new DefaultContextCache(-1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void maxCacheSizeZero() { - new DefaultContextCache(0); + assertThatIllegalArgumentException().isThrownBy(() -> + new DefaultContextCache(0)); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java index c52db5ba385..386d4aa6e16 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java @@ -29,8 +29,8 @@ import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.transaction.AfterTransaction; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; /** @@ -52,13 +52,9 @@ public class TransactionalAfterTestMethodSqlScriptsTests extends AbstractTransac @AfterTransaction public void afterTransaction() { if ("test01".equals(testName.getMethodName())) { - try { - assertNumUsers(99); - fail("Should throw a BadSqlGrammarException after test01, assuming 'drop-schema.sql' was executed"); - } - catch (BadSqlGrammarException e) { - /* expected */ - } + // Should throw a BadSqlGrammarException after test01, assuming 'drop-schema.sql' was executed + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> + assertNumUsers(99)); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java index 52cf76bf2f0..832a19705cc 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java @@ -25,6 +25,7 @@ import org.junit.runners.model.FrameworkMethod; import org.springframework.test.annotation.Timed; import org.springframework.test.context.TestContextManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -36,7 +37,7 @@ import static org.junit.Assert.assertEquals; */ public class SpringJUnit4ClassRunnerTests { - @Test(expected = Exception.class) + @Test public void checkThatExceptionsAreNotSilentlySwallowed() throws Exception { SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()) { @@ -52,7 +53,8 @@ public class SpringJUnit4ClassRunnerTests { }; } }; - runner.createTest(); + assertThatExceptionOfType(Exception.class).isThrownBy( + runner::createTest); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java index d90ea7f1eec..bf1be54d122 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java @@ -32,6 +32,7 @@ import org.springframework.test.context.junit4.orm.domain.Person; import org.springframework.test.context.junit4.orm.service.PersonService; import org.springframework.transaction.annotation.Transactional; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; @@ -98,9 +99,10 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp assertNotNull("Juergen's ID should have been set", juergen.getId()); } - @Test(expected = ConstraintViolationException.class) + @Test public void saveJuergenWithNullDriversLicense() { - personService.save(new Person(JUERGEN)); + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> + personService.save(new Person(JUERGEN))); } @Test @@ -111,17 +113,19 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp // finally flushed (i.e., in production code) } - @Test(expected = ConstraintViolationException.class) + @Test public void updateSamWithNullDriversLicenseWithSessionFlush() throws Throwable { updateSamWithNullDriversLicense(); - // Manual flush is required to avoid false positive in test - try { - sessionFactory.getCurrentSession().flush(); - } - catch (PersistenceException ex) { - // Wrapped in Hibernate 5.2, with the constraint violation as cause - throw ex.getCause(); - } + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> { + // Manual flush is required to avoid false positive in test + try { + sessionFactory.getCurrentSession().flush(); + } + catch (PersistenceException ex) { + // Wrapped in Hibernate 5.2, with the constraint violation as cause + throw ex.getCause(); + } + }); } private void updateSamWithNullDriversLicense() { diff --git a/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java index 55faa5746bc..8f85911bed1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java @@ -31,6 +31,8 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfilesResolver; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertArrayEquals; import static org.springframework.test.context.support.ActiveProfilesUtils.resolveActiveProfiles; @@ -189,17 +191,19 @@ public class ActiveProfilesUtilsTests extends AbstractContextConfigurationUtilsT /** * @since 4.0 */ - @Test(expected = AnnotationConfigurationException.class) + @Test public void resolveActiveProfilesWithConflictingProfilesAndValue() { - resolveActiveProfiles(ConflictingProfilesAndValueTestCase.class); + assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() -> + resolveActiveProfiles(ConflictingProfilesAndValueTestCase.class)); } /** * @since 4.0 */ - @Test(expected = IllegalStateException.class) + @Test public void resolveActiveProfilesWithResolverWithoutDefaultConstructor() { - resolveActiveProfiles(NoDefaultConstructorActiveProfilesResolverTestCase.class); + assertThatIllegalStateException().isThrownBy(() -> + resolveActiveProfiles(NoDefaultConstructorActiveProfilesResolverTestCase.class)); } /** diff --git a/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java index b2871282c08..bf9685fb395 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -38,9 +39,10 @@ import static org.springframework.test.context.support.AnnotationConfigContextLo */ public class AnnotationConfigContextLoaderUtilsTests { - @Test(expected = IllegalArgumentException.class) + @Test public void detectDefaultConfigurationClassesWithNullDeclaringClass() { - detectDefaultConfigurationClasses(null); + assertThatIllegalArgumentException().isThrownBy(() -> + detectDefaultConfigurationClasses(null)); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java index 596be728ade..639d8190f23 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java @@ -31,6 +31,7 @@ import org.springframework.test.context.ContextConfigurationAttributes; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.ContextLoader; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; @@ -38,7 +39,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.springframework.test.context.support.ContextLoaderUtils.GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX; import static org.springframework.test.context.support.ContextLoaderUtils.buildContextHierarchyMap; import static org.springframework.test.context.support.ContextLoaderUtils.resolveContextHierarchyAttributes; @@ -57,14 +57,16 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf // } } - @Test(expected = IllegalStateException.class) + @Test public void resolveContextHierarchyAttributesForSingleTestClassWithContextConfigurationAndContextHierarchy() { - resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchy.class); + assertThatIllegalStateException().isThrownBy(() -> + resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchy.class)); } - @Test(expected = IllegalStateException.class) + @Test public void resolveContextHierarchyAttributesForSingleTestClassWithContextConfigurationAndContextHierarchyOnSingleMetaAnnotation() { - resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchyOnSingleMetaAnnotation.class); + assertThatIllegalStateException().isThrownBy(() -> + resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchyOnSingleMetaAnnotation.class)); } @Test @@ -319,16 +321,10 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf } private void assertContextConfigEntriesAreNotUnique(Class testClass) { - try { - buildContextHierarchyMap(testClass); - fail("Should throw an IllegalStateException"); - } - catch (IllegalStateException e) { - String msg = String.format( - "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.", - testClass.getName()); - assertEquals(msg, e.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + buildContextHierarchyMap(testClass)) + .withMessage(String.format( + "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.", testClass.getName())); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java index 2fb70f2a76e..c96a8fab5d8 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java @@ -27,6 +27,8 @@ import org.springframework.test.context.ContextLoader; import org.springframework.test.context.MergedContextConfiguration; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -103,10 +105,10 @@ public class DelegatingSmartContextLoaderTests { // --- SmartContextLoader - loadContext() ---------------------------------- - @Test(expected = IllegalArgumentException.class) + @Test public void loadContextWithNullConfig() throws Exception { - MergedContextConfiguration mergedConfig = null; - loader.loadContext(mergedConfig); + assertThatIllegalArgumentException().isThrownBy(() -> + loader.loadContext((MergedContextConfiguration) null)); } @Test @@ -160,14 +162,16 @@ public class DelegatingSmartContextLoaderTests { // --- ContextLoader ------------------------------------------------------- - @Test(expected = UnsupportedOperationException.class) + @Test public void processLocations() { - loader.processLocations(getClass(), EMPTY_STRING_ARRAY); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + loader.processLocations(getClass(), EMPTY_STRING_ARRAY)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void loadContextFromLocations() throws Exception { - loader.loadContext(EMPTY_STRING_ARRAY); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + loader.loadContext(EMPTY_STRING_ARRAY)); } diff --git a/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java b/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java index 0169b0e60b1..66a10939552 100644 --- a/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java @@ -34,10 +34,10 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.SimpleTransactionStatus; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; @@ -86,14 +86,9 @@ public class TransactionalTestExecutionListenerTests { assertFalse("callback should not have been invoked", instance.invoked()); TransactionContextHolder.removeCurrentTransactionContext(); - try { - listener.beforeTestMethod(testContext); - fail("Should have thrown an IllegalStateException"); - } - catch (IllegalStateException e) { - assertTrue(e.getMessage().startsWith( - "Failed to retrieve PlatformTransactionManager for @Transactional test")); - } + assertThatIllegalStateException().isThrownBy(() -> + listener.beforeTestMethod(testContext)) + .withMessageStartingWith("Failed to retrieve PlatformTransactionManager for @Transactional test"); } @Test 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 7ef84147f74..a83b86d431e 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,6 +21,7 @@ import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; +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; @@ -40,9 +41,10 @@ public class AopTestUtilsTests { private final FooImpl foo = new FooImpl(); - @Test(expected = IllegalArgumentException.class) + @Test public void getTargetObjectForNull() { - getTargetObject(null); + assertThatIllegalArgumentException().isThrownBy(() -> + getTargetObject(null)); } @Test @@ -75,9 +77,10 @@ public class AopTestUtilsTests { assertNotSame(foo, target); } - @Test(expected = IllegalArgumentException.class) + @Test public void getUltimateTargetObjectForNull() { - getUltimateTargetObject(null); + assertThatIllegalArgumentException().isThrownBy(() -> + getUltimateTargetObject(null)); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java index b85325897df..5c4568309a4 100644 --- a/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java @@ -192,19 +192,22 @@ public class ReflectionTestUtilsTests { assertNull("'favorite number' (package field)", person.getFavoriteNumber()); } - @Test(expected = IllegalArgumentException.class) + @Test public void setFieldWithNullValueForPrimitiveLong() throws Exception { - setField(person, "id", null, long.class); + assertThatIllegalArgumentException().isThrownBy(() -> + setField(person, "id", null, long.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setFieldWithNullValueForPrimitiveInt() throws Exception { - setField(person, "age", null, int.class); + assertThatIllegalArgumentException().isThrownBy(() -> + setField(person, "age", null, int.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setFieldWithNullValueForPrimitiveBoolean() throws Exception { - setField(person, "likesPets", null, boolean.class); + assertThatIllegalArgumentException().isThrownBy(() -> + setField(person, "likesPets", null, boolean.class)); } @Test @@ -307,19 +310,22 @@ public class ReflectionTestUtilsTests { assertNull("'favorite number' (protected method for a Number)", person.getFavoriteNumber()); } - @Test(expected = IllegalArgumentException.class) + @Test public void invokeSetterMethodWithNullValueForPrimitiveLong() throws Exception { - invokeSetterMethod(person, "id", null, long.class); + assertThatIllegalArgumentException().isThrownBy(() -> + invokeSetterMethod(person, "id", null, long.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void invokeSetterMethodWithNullValueForPrimitiveInt() throws Exception { - invokeSetterMethod(person, "age", null, int.class); + assertThatIllegalArgumentException().isThrownBy(() -> + invokeSetterMethod(person, "age", null, int.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void invokeSetterMethodWithNullValueForPrimitiveBoolean() throws Exception { - invokeSetterMethod(person, "likesPets", null, boolean.class); + assertThatIllegalArgumentException().isThrownBy(() -> + invokeSetterMethod(person, "likesPets", null, boolean.class)); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java b/spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java index 671f938d0ea..89c5053af86 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.test.web.client.MockRestServiceServer.MockRestServiceServerBuilder; import org.springframework.web.client.RestTemplate; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; import static org.springframework.http.HttpMethod.POST; import static org.springframework.test.web.client.ExpectedCount.once; @@ -63,14 +63,15 @@ public class MockRestServiceServerTests { server.verify(); } - @Test(expected = AssertionError.class) + @Test public void exactExpectOrder() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate) .ignoreExpectOrder(false).build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); server.expect(requestTo("/bar")).andRespond(withSuccess()); - this.restTemplate.getForObject("/bar", Void.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.restTemplate.getForObject("/bar", Void.class)); } @Test @@ -143,21 +144,13 @@ public class MockRestServiceServerTests { server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess()); this.restTemplate.postForEntity("/remoteurl", null, String.class); - try { - this.restTemplate.postForEntity("/remoteurl", null, String.class); - fail("Expected assertion error"); - } - catch (AssertionError error) { - assertThat(error.getMessage()).startsWith("No further requests expected"); - } + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.restTemplate.postForEntity("/remoteurl", null, String.class)) + .withMessageStartingWith("No further requests expected"); - try { - server.verify(); - fail("Expected verify failure"); - } - catch (AssertionError error) { - assertThat(error.getMessage()).startsWith("Some requests did not execute successfully"); - } + assertThatExceptionOfType(AssertionError.class).isThrownBy( + server::verify) + .withMessageStartingWith("Some requests did not execute successfully"); } } 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 54877c29592..dd57c3d8609 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 @@ -26,6 +26,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.hasXPath; /** @@ -52,18 +53,20 @@ public class ContentRequestMatchersTests { MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_JSON).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testContentTypeNoMatch1() throws Exception { this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); - MockRestRequestMatchers.content().contentType("application/xml").match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers.content().contentType("application/xml").match(this.request)); } - @Test(expected = AssertionError.class) + @Test public void testContentTypeNoMatch2() throws Exception { this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); - MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request)); } @Test @@ -73,11 +76,12 @@ public class ContentRequestMatchersTests { MockRestRequestMatchers.content().string("test").match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testStringNoMatch() throws Exception { this.request.getBody().write("test".getBytes()); - MockRestRequestMatchers.content().string("Test").match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers.content().string("Test").match(this.request)); } @Test @@ -88,11 +92,12 @@ public class ContentRequestMatchersTests { MockRestRequestMatchers.content().bytes(content).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testBytesNoMatch() throws Exception { this.request.getBody().write("test".getBytes()); - MockRestRequestMatchers.content().bytes("Test".getBytes()).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers.content().bytes("Test".getBytes()).match(this.request)); } @Test @@ -119,11 +124,12 @@ public class ContentRequestMatchersTests { MockRestRequestMatchers.content().xml(content).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testXmlNoMatch() throws Exception { this.request.getBody().write("11".getBytes()); - MockRestRequestMatchers.content().xml("22").match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers.content().xml("22").match(this.request)); } @Test @@ -134,12 +140,12 @@ public class ContentRequestMatchersTests { MockRestRequestMatchers.content().node(hasXPath("/foo/bar")).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testNodeMatcherNoMatch() throws Exception { String content = "baz"; this.request.getBody().write(content.getBytes()); - - MockRestRequestMatchers.content().node(hasXPath("/foo/bar/bar")).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers.content().node(hasXPath("/foo/bar/bar")).match(this.request)); } @Test @@ -164,30 +170,33 @@ public class ContentRequestMatchersTests { .match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testJsonLenientNoMatch() throws Exception { String content = "{\n \"bar\" : \"foo\" \n}"; this.request.getBody().write(content.getBytes()); - MockRestRequestMatchers - .content() - .json("{\n \"foo\" : \"bar\" \n}") - .match(this.request); - MockRestRequestMatchers - .content() - .json("{\n \"foo\" : \"bar\" \n}", false) - .match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers + .content() + .json("{\n \"foo\" : \"bar\" \n}") + .match(this.request)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers + .content() + .json("{\n \"foo\" : \"bar\" \n}", false) + .match(this.request)); } - @Test(expected = AssertionError.class) + @Test public void testJsonStrictNoMatch() throws Exception { String content = "{\n \"foo array\":[\"first\",\"second\"] , \"someExtraProperty\": \"which is NOT allowed\" \n}"; this.request.getBody().write(content.getBytes()); - MockRestRequestMatchers - .content() - .json("{\n \"foo array\":[\"second\",\"first\"] \n}", true) - .match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + MockRestRequestMatchers + .content() + .json("{\n \"foo array\":[\"second\",\"first\"] \n}", true) + .match(this.request)); } } 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 b580665dac4..67b9f53f988 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 @@ -22,6 +22,7 @@ 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; /** @@ -55,9 +56,10 @@ public class JsonPathRequestMatchersTests { } - @Test(expected = AssertionError.class) + @Test public void valueWithMismatch() throws Exception { - new JsonPathRequestMatchers("$.str").value("bogus").match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").value("bogus").match(request)); } @Test @@ -80,9 +82,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.num").value(equalTo(5.0f), Float.class).match(request); } - @Test(expected = AssertionError.class) + @Test public void valueWithMatcherAndMismatch() throws Exception { - new JsonPathRequestMatchers("$.str").value(equalTo("bogus")).match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").value(equalTo("bogus")).match(request)); } @Test @@ -100,9 +103,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.emptyMap").exists().match(request); } - @Test(expected = AssertionError.class) + @Test public void existsNoMatch() throws Exception { - new JsonPathRequestMatchers("$.bogus").exists().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.bogus").exists().match(request)); } @Test @@ -110,19 +114,22 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.bogus").doesNotExist().match(request); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistNoMatch() throws Exception { - new JsonPathRequestMatchers("$.str").doesNotExist().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").doesNotExist().match(request)); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistForAnEmptyArray() throws Exception { - new JsonPathRequestMatchers("$.emptyArray").doesNotExist().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.emptyArray").doesNotExist().match(request)); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistForAnEmptyMap() throws Exception { - new JsonPathRequestMatchers("$.emptyMap").doesNotExist().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.emptyMap").doesNotExist().match(request)); } @Test @@ -165,19 +172,22 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.colorMap").isNotEmpty().match(request); } - @Test(expected = AssertionError.class) + @Test public void isNotEmptyForAnEmptyString() throws Exception { - new JsonPathRequestMatchers("$.emptyString").isNotEmpty().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.emptyString").isNotEmpty().match(request)); } - @Test(expected = AssertionError.class) + @Test public void isNotEmptyForAnEmptyArray() throws Exception { - new JsonPathRequestMatchers("$.emptyArray").isNotEmpty().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.emptyArray").isNotEmpty().match(request)); } - @Test(expected = AssertionError.class) + @Test public void isNotEmptyForAnEmptyMap() throws Exception { - new JsonPathRequestMatchers("$.emptyMap").isNotEmpty().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.emptyMap").isNotEmpty().match(request)); } @Test @@ -190,9 +200,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.emptyArray").isArray().match(request); } - @Test(expected = AssertionError.class) + @Test public void isArrayNoMatch() throws Exception { - new JsonPathRequestMatchers("$.str").isArray().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").isArray().match(request)); } @Test @@ -205,9 +216,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.emptyMap").isMap().match(request); } - @Test(expected = AssertionError.class) + @Test public void isMapNoMatch() throws Exception { - new JsonPathRequestMatchers("$.str").isMap().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").isMap().match(request)); } @Test @@ -215,9 +227,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.bool").isBoolean().match(request); } - @Test(expected = AssertionError.class) + @Test public void isBooleanNoMatch() throws Exception { - new JsonPathRequestMatchers("$.str").isBoolean().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").isBoolean().match(request)); } @Test @@ -225,9 +238,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.num").isNumber().match(request); } - @Test(expected = AssertionError.class) + @Test public void isNumberNoMatch() throws Exception { - new JsonPathRequestMatchers("$.str").isNumber().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.str").isNumber().match(request)); } @Test @@ -235,9 +249,10 @@ public class JsonPathRequestMatchersTests { new JsonPathRequestMatchers("$.str").isString().match(request); } - @Test(expected = AssertionError.class) + @Test public void isStringNoMatch() throws Exception { - new JsonPathRequestMatchers("$.arr").isString().match(request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathRequestMatchers("$.arr").isString().match(request)); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/match/XpathRequestMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/client/match/XpathRequestMatchersTests.java index 4273d2d11cf..1fe94cab41d 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/match/XpathRequestMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/match/XpathRequestMatchersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 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. @@ -24,6 +24,8 @@ import org.junit.Test; import org.springframework.mock.http.client.MockClientHttpRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * Unit tests for {@link XpathRequestMatchers}. * @@ -48,9 +50,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testNodeMatcherNoMatch() throws Exception { - new XpathRequestMatchers("/foo/bar", null).node(Matchers.nullValue()).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/bar", null).node(Matchers.nullValue()).match(this.request)); } @Test @@ -58,9 +61,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/bar", null).exists().match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testExistsNoMatch() throws Exception { - new XpathRequestMatchers("/foo/Bar", null).exists().match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/Bar", null).exists().match(this.request)); } @Test @@ -68,9 +72,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/Bar", null).doesNotExist().match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testDoesNotExistNoMatch() throws Exception { - new XpathRequestMatchers("/foo/bar", null).doesNotExist().match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/bar", null).doesNotExist().match(this.request)); } @Test @@ -78,9 +83,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/bar", null).nodeCount(2).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testNodeCountNoMatch() throws Exception { - new XpathRequestMatchers("/foo/bar", null).nodeCount(1).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/bar", null).nodeCount(1).match(this.request)); } @Test @@ -88,9 +94,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/bar[1]", null).string("111").match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testStringNoMatch() throws Exception { - new XpathRequestMatchers("/foo/bar[1]", null).string("112").match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/bar[1]", null).string("112").match(this.request)); } @Test @@ -98,9 +105,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/bar[1]", null).number(111.0).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testNumberNoMatch() throws Exception { - new XpathRequestMatchers("/foo/bar[1]", null).number(111.1).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/bar[1]", null).number(111.1).match(this.request)); } @Test @@ -108,9 +116,10 @@ public class XpathRequestMatchersTests { new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(true).match(this.request); } - @Test(expected = AssertionError.class) + @Test public void testBooleanNoMatch() throws Exception { - new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(false).match(this.request); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(false).match(this.request)); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java b/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java index 8f7fa9ec595..246c683a7c9 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java @@ -34,6 +34,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.util.FileCopyUtils; import org.springframework.web.client.RestTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.client.ExpectedCount.manyTimes; @@ -118,7 +119,7 @@ public class SampleTests { this.mockServer.verify(); } - @Test(expected = AssertionError.class) + @Test public void expectNeverViolated() { String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}"; @@ -129,7 +130,8 @@ public class SampleTests { .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); this.restTemplate.getForObject("/composers/{id}", Person.class, 42); - this.restTemplate.getForObject("/composers/{id}", Person.class, 43); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.restTemplate.getForObject("/composers/{id}", Person.class, 43)); } @Test 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 e159f513c44..e9a35b4697d 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 @@ -33,10 +33,9 @@ import org.springframework.http.MediaType; import org.springframework.mock.http.client.reactive.MockClientHttpRequest; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -55,29 +54,17 @@ public class HeaderAssertionTests { // Success assertions.valueEquals("foo", "bar"); - try { - assertions.valueEquals("what?!", "bar"); - fail("Missing header expected"); - } - catch (AssertionError error) { - // expected - } + // Missing header + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.valueEquals("what?!", "bar")); - try { - assertions.valueEquals("foo", "what?!"); - fail("Wrong value expected"); - } - catch (AssertionError error) { - // expected - } + // Wrong value + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.valueEquals("foo", "what?!")); - try { - assertions.valueEquals("foo", "bar", "what?!"); - fail("Wrong # of values expected"); - } - catch (AssertionError error) { - // expected - } + // Wrong # of values + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.valueEquals("foo", "bar", "what?!")); } @Test @@ -90,21 +77,13 @@ public class HeaderAssertionTests { // Success assertions.valueEquals("foo", "bar", "baz"); - try { - assertions.valueEquals("foo", "bar", "what?!"); - fail("Wrong value expected"); - } - catch (AssertionError error) { - // expected - } + // Wrong value + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.valueEquals("foo", "bar", "what?!")); - try { - assertions.valueEquals("foo", "bar"); - fail("Too few values expected"); - } - catch (AssertionError error) { - // expected - } + // Too few values + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.valueEquals("foo", "bar")); } @@ -117,16 +96,12 @@ public class HeaderAssertionTests { // Success assertions.valueMatches("Content-Type", ".*UTF-8.*"); - try { - assertions.valueMatches("Content-Type", ".*ISO-8859-1.*"); - fail("Wrong pattern expected"); - } - catch (AssertionError error) { - Throwable cause = error.getCause(); - assertNotNull(cause); - assertEquals("Response header 'Content-Type'=[application/json;charset=UTF-8] " + - "does not match [.*ISO-8859-1.*]", cause.getMessage()); - } + // Wrong pattern + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.valueMatches("Content-Type", ".*ISO-8859-1.*")) + .satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header " + + "'Content-Type'=[application/json;charset=UTF-8] does not match " + + "[.*ISO-8859-1.*]")); } @Test @@ -147,15 +122,10 @@ public class HeaderAssertionTests { // Success assertions.exists("Content-Type"); - try { - assertions.exists("Framework"); - fail("Header should not exist"); - } - catch (AssertionError error) { - Throwable cause = error.getCause(); - assertNotNull(cause); - assertEquals("Response header 'Framework' does not exist", cause.getMessage()); - } + // Header should not exist + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.exists("Framework")) + .satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header 'Framework' does not exist")); } @Test @@ -167,16 +137,11 @@ public class HeaderAssertionTests { // Success assertions.doesNotExist("Framework"); - try { - assertions.doesNotExist("Content-Type"); - fail("Existing header expected"); - } - catch (AssertionError error) { - Throwable cause = error.getCause(); - assertNotNull(cause); - assertEquals("Response header 'Content-Type' exists with " + - "value=[application/json;charset=UTF-8]", cause.getMessage()); - } + // Existing header + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.doesNotExist("Content-Type")) + .satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header " + + "'Content-Type' exists with value=[application/json;charset=UTF-8]")); } @Test @@ -188,16 +153,11 @@ public class HeaderAssertionTests { // Success assertions.contentTypeCompatibleWith(MediaType.parseMediaType("application/*")); - try { - assertions.contentTypeCompatibleWith(MediaType.TEXT_XML); - fail("MediaTypes not compatible expected"); - } - catch (AssertionError error) { - Throwable cause = error.getCause(); - assertNotNull(cause); - assertEquals("Response header 'Content-Type'=[application/xml] " + - "is not compatible with [text/xml]", cause.getMessage()); - } + // MediaTypes not compatible + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.contentTypeCompatibleWith(MediaType.TEXT_XML)) + .satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header " + + "'Content-Type'=[application/xml] is not compatible with [text/xml]")); } @Test @@ -211,13 +171,9 @@ public class HeaderAssertionTests { // Success assertions.cacheControl(control); - try { - assertions.cacheControl(CacheControl.noStore()); - fail("Wrong value expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong value + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.cacheControl(CacheControl.noStore())); } @Test @@ -227,13 +183,10 @@ public class HeaderAssertionTests { headers.setExpires(expires); HeaderAssertions assertions = headerAssertions(headers); assertions.expires(expires.toInstant().toEpochMilli()); - try { - assertions.expires(expires.toInstant().toEpochMilli() + 1); - fail("Wrong value expected"); - } - catch (AssertionError error) { - // Expected - } + + // Wrong value + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.expires(expires.toInstant().toEpochMilli() + 1)); } @Test @@ -243,13 +196,10 @@ public class HeaderAssertionTests { headers.setLastModified(lastModified.toInstant().toEpochMilli()); HeaderAssertions assertions = headerAssertions(headers); assertions.lastModified(lastModified.toInstant().toEpochMilli()); - try { - assertions.lastModified(lastModified.toInstant().toEpochMilli() + 1); - fail("Wrong value expected"); - } - catch (AssertionError error) { - // Expected - } + + // Wrong value + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.lastModified(lastModified.toInstant().toEpochMilli() + 1)); } private HeaderAssertions headerAssertions(HttpHeaders responseHeaders) { diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/StatusAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/StatusAssertionTests.java index 8a13d353283..6f37e867a97 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/StatusAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/StatusAssertionTests.java @@ -27,9 +27,9 @@ import org.springframework.http.HttpStatus; import org.springframework.mock.http.client.reactive.MockClientHttpRequest; import org.springframework.mock.http.client.reactive.MockClientHttpResponse; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -46,21 +46,13 @@ public class StatusAssertionTests { assertions.isEqualTo(HttpStatus.CONFLICT); assertions.isEqualTo(409); - try { - assertions.isEqualTo(HttpStatus.REQUEST_TIMEOUT); - fail("Wrong status expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong status + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.isEqualTo(HttpStatus.REQUEST_TIMEOUT)); - try { - assertions.isEqualTo(408); - fail("Wrong status value expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong status value + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.isEqualTo(408)); } @Test @@ -70,13 +62,9 @@ public class StatusAssertionTests { // Success assertions.reasonEquals("Conflict"); - try { - assertions.reasonEquals("Request Timeout"); - fail("Wrong reason expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong reason + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.reasonEquals("Request Timeout")); } @Test @@ -86,13 +74,10 @@ public class StatusAssertionTests { // Success assertions.is1xxInformational(); - try { - assertions.is2xxSuccessful(); - fail("Wrong series expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong series + + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.is2xxSuccessful()); } @Test @@ -102,13 +87,9 @@ public class StatusAssertionTests { // Success assertions.is2xxSuccessful(); - try { - assertions.is5xxServerError(); - fail("Wrong series expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong series + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.is5xxServerError()); } @Test @@ -118,13 +99,9 @@ public class StatusAssertionTests { // Success assertions.is3xxRedirection(); - try { - assertions.is2xxSuccessful(); - fail("Wrong series expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong series + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.is2xxSuccessful()); } @Test @@ -134,13 +111,9 @@ public class StatusAssertionTests { // Success assertions.is4xxClientError(); - try { - assertions.is2xxSuccessful(); - fail("Wrong series expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong series + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.is2xxSuccessful()); } @Test @@ -150,13 +123,9 @@ public class StatusAssertionTests { // Success assertions.is5xxServerError(); - try { - assertions.is2xxSuccessful(); - fail("Wrong series expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong series + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.is2xxSuccessful()); } @Test @@ -167,13 +136,9 @@ public class StatusAssertionTests { assertions.value(equalTo(409)); assertions.value(greaterThan(400)); - try { - assertions.value(equalTo(200)); - fail("Wrong status expected"); - } - catch (AssertionError error) { - // Expected - } + // Wrong status + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + assertions.value(equalTo(200))); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java index 453f9b91993..67c07f6e5df 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.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. @@ -22,6 +22,8 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; + /** * Test fixture for {@link DefaultMvcResult}. * @@ -38,9 +40,10 @@ public class DefaultMvcResultTests { this.mvcResult.getAsyncResult(); } - @Test(expected = IllegalStateException.class) + @Test public void getAsyncResultFailure() { - this.mvcResult.getAsyncResult(0); + assertThatIllegalStateException().isThrownBy(() -> + this.mvcResult.getAsyncResult(0)); } } 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 2c84ad42c72..4d00dc24517 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 @@ -46,6 +46,7 @@ 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.assertThatIllegalArgumentException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -86,19 +87,22 @@ public class HtmlUnitRequestBuilderTests { // --- constructor - @Test(expected = IllegalArgumentException.class) + @Test public void constructorNullSessions() { - new HtmlUnitRequestBuilder(null, webClient, webRequest); + assertThatIllegalArgumentException().isThrownBy(() -> + new HtmlUnitRequestBuilder(null, webClient, webRequest)); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorNullWebClient() { - new HtmlUnitRequestBuilder(sessions, null, webRequest); + assertThatIllegalArgumentException().isThrownBy(() -> + new HtmlUnitRequestBuilder(sessions, null, webRequest)); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorNullWebRequest() { - new HtmlUnitRequestBuilder(sessions, webClient, null); + assertThatIllegalArgumentException().isThrownBy(() -> + new HtmlUnitRequestBuilder(sessions, webClient, null)); } @@ -184,11 +188,12 @@ public class HtmlUnitRequestBuilderTests { assertThat(contextPath, equalTo("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void buildRequestContextPathInvalid() { requestBuilder.setContextPath("/invalid"); - requestBuilder.buildRequest(servletContext).getContextPath(); + assertThatIllegalArgumentException().isThrownBy(() -> + requestBuilder.buildRequest(servletContext).getContextPath()); } @Test @@ -823,14 +828,16 @@ public class HtmlUnitRequestBuilderTests { assertThat(getContextPath(), isEmptyString()); } - @Test(expected = IllegalArgumentException.class) + @Test public void setContextPathDoesNotStartWithSlash() { - requestBuilder.setContextPath("abc/def"); + assertThatIllegalArgumentException().isThrownBy(() -> + requestBuilder.setContextPath("abc/def")); } - @Test(expected = IllegalArgumentException.class) + @Test public void setContextPathEndsWithSlash() { - requestBuilder.setContextPath("/abc/def/"); + assertThatIllegalArgumentException().isThrownBy(() -> + requestBuilder.setContextPath("/abc/def/")); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java index a988beb7342..bdc605e6972 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,6 +40,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.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; @@ -75,14 +76,16 @@ public class MockMvcConnectionBuilderSupportTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorMockMvcNull() { - new MockMvcWebConnectionBuilderSupport((MockMvc) null){}; + assertThatIllegalArgumentException().isThrownBy(() -> + new MockMvcWebConnectionBuilderSupport((MockMvc) null){}); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorContextNull() { - new MockMvcWebConnectionBuilderSupport((WebApplicationContext) null){}; + assertThatIllegalArgumentException().isThrownBy(() -> + new MockMvcWebConnectionBuilderSupport((WebApplicationContext) null){}); } @Test 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 4cef8335de4..69fed6a802e 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,6 +48,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.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; @@ -77,14 +78,16 @@ public class MockMvcWebClientBuilderTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void mockMvcSetupNull() { - MockMvcWebClientBuilder.mockMvcSetup(null); + assertThatIllegalArgumentException().isThrownBy(() -> + MockMvcWebClientBuilder.mockMvcSetup(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void webAppContextSetupNull() { - MockMvcWebClientBuilder.webAppContextSetup(null); + assertThatIllegalArgumentException().isThrownBy(() -> + MockMvcWebClientBuilder.webAppContextSetup(null)); } @Test 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 9dbef95859e..e4bb818e4a7 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 @@ -26,10 +26,11 @@ import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; 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; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * Integration tests for {@link MockMvcWebConnection}. @@ -62,21 +63,15 @@ public class MockMvcWebConnectionTests { @Test public void contextPathEmpty() throws IOException { this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, "")); - try { - this.webClient.getPage("http://localhost/context/a"); - fail("Empty context path (root context) should not match to a URL with a context path"); - } - catch (FailingHttpStatusCodeException ex) { - assertEquals(404, ex.getStatusCode()); - } + // Empty context path (root context) should not match to a URL with a context path + assertThatExceptionOfType(FailingHttpStatusCodeException.class).isThrownBy(() -> + this.webClient.getPage("http://localhost/context/a")) + .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404)); this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient)); - try { - this.webClient.getPage("http://localhost/context/a"); - fail("No context is the same providing an empty context path"); - } - catch (FailingHttpStatusCodeException ex) { - assertEquals(404, ex.getStatusCode()); - } + // No context is the same providing an empty context path + assertThatExceptionOfType(FailingHttpStatusCodeException.class).isThrownBy(() -> + this.webClient.getPage("http://localhost/context/a")) + .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404)); } @Test @@ -86,16 +81,18 @@ public class MockMvcWebConnectionTests { assertThat(page.getWebResponse().getContentAsString(), equalTo("hello")); } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings("resource") public void contextPathDoesNotStartWithSlash() throws IOException { - new MockMvcWebConnection(this.mockMvc, this.webClient, "context"); + assertThatIllegalArgumentException().isThrownBy(() -> + new MockMvcWebConnection(this.mockMvc, this.webClient, "context")); } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings("resource") public void contextPathEndsWithSlash() throws IOException { - new MockMvcWebConnection(this.mockMvc, this.webClient, "/context/"); + assertThatIllegalArgumentException().isThrownBy(() -> + new MockMvcWebConnection(this.mockMvc, this.webClient, "/context/")); } } 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 7af4b1c6912..697213f622a 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,6 +29,7 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletResponse; +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; @@ -58,14 +59,16 @@ public class MockWebResponseBuilderTests { // --- constructor - @Test(expected = IllegalArgumentException.class) + @Test public void constructorWithNullWebRequest() { - new MockWebResponseBuilder(0L, null, this.response); + assertThatIllegalArgumentException().isThrownBy(() -> + new MockWebResponseBuilder(0L, null, this.response)); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorWithNullResponse() throws Exception { - new MockWebResponseBuilder(0L, new WebRequest(new URL("http://example.com:80/test/this/here")), null); + assertThatIllegalArgumentException().isThrownBy(() -> + new MockWebResponseBuilder(0L, new WebRequest(new URL("http://example.com:80/test/this/here")), null)); } 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 f2afe379ae9..afc80171d1c 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,6 +40,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.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; @@ -75,14 +76,16 @@ public class MockMvcHtmlUnitDriverBuilderTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void webAppContextSetupNull() { - MockMvcHtmlUnitDriverBuilder.webAppContextSetup(null); + assertThatIllegalArgumentException().isThrownBy(() -> + MockMvcHtmlUnitDriverBuilder.webAppContextSetup(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void mockMvcSetupNull() { - MockMvcHtmlUnitDriverBuilder.mockMvcSetup(null); + assertThatIllegalArgumentException().isThrownBy(() -> + MockMvcHtmlUnitDriverBuilder.mockMvcSetup(null)); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/ContentResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/ContentResultMatchersTests.java index 17fb1fd9c72..abfb47a4ebd 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/ContentResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/ContentResultMatchersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 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. @@ -22,6 +22,8 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.StubMvcResult; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Rossen Stoyanchev */ @@ -32,9 +34,10 @@ public class ContentResultMatchersTests { new ContentResultMatchers().contentType("application/json;charset=UTF-8").match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void typeNoMatch() throws Exception { - new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult())); } @Test @@ -42,9 +45,10 @@ public class ContentResultMatchersTests { new ContentResultMatchers().encoding("UTF-8").match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void encodingNoMatch() throws Exception { - new ContentResultMatchers().encoding("ISO-8859-1").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().encoding("ISO-8859-1").match(getStubMvcResult())); } @Test @@ -52,9 +56,10 @@ public class ContentResultMatchersTests { new ContentResultMatchers().string(new String(CONTENT.getBytes("UTF-8"))).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void stringNoMatch() throws Exception { - new ContentResultMatchers().encoding("bogus").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().encoding("bogus").match(getStubMvcResult())); } @Test @@ -63,9 +68,10 @@ public class ContentResultMatchersTests { new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void stringMatcherNoMatch() throws Exception { - new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult())); } @Test @@ -73,9 +79,10 @@ public class ContentResultMatchersTests { new ContentResultMatchers().bytes(CONTENT.getBytes("UTF-8")).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void bytesNoMatch() throws Exception { - new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult())); } @Test @@ -90,14 +97,16 @@ public class ContentResultMatchersTests { new ContentResultMatchers().json("{\n \"foo array\":[\"foo\",\"bar\"], \"foo\":\"bar\" \n}", true).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void jsonLenientNoMatch() throws Exception { - new ContentResultMatchers().json("{\n\"fooo\":\"bar\"\n}").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().json("{\n\"fooo\":\"bar\"\n}").match(getStubMvcResult())); } - @Test(expected = AssertionError.class) + @Test public void jsonStrictNoMatch() throws Exception { - new ContentResultMatchers().json("{\"foo\":\"bar\", \"foo array\":[\"bar\",\"foo\"]}", true).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new ContentResultMatchers().json("{\"foo\":\"bar\", \"foo array\":[\"bar\",\"foo\"]}", true).match(getStubMvcResult())); } private static final String CONTENT = "{\"foo\":\"bar\",\"foo array\":[\"foo\",\"bar\"]}"; diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchersTests.java index abcd167429a..5d104ace5a1 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 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. @@ -21,6 +21,8 @@ import org.junit.Test; import org.springframework.test.web.servlet.StubMvcResult; import org.springframework.web.servlet.FlashMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Craig Walls */ @@ -31,9 +33,10 @@ public class FlashAttributeResultMatchersTests { new FlashAttributeResultMatchers().attributeExists("good").match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void attributeExists_doesntExist() throws Exception { - new FlashAttributeResultMatchers().attributeExists("bad").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new FlashAttributeResultMatchers().attributeExists("bad").match(getStubMvcResult())); } @Test @@ -41,9 +44,10 @@ public class FlashAttributeResultMatchersTests { new FlashAttributeResultMatchers().attribute("good", "good").match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void attribute_incorrectValue() throws Exception { - new FlashAttributeResultMatchers().attribute("good", "not good").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new FlashAttributeResultMatchers().attribute("good", "not good").match(getStubMvcResult())); } private StubMvcResult getStubMvcResult() { diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java index aa4f9150161..cfc14d6153d 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java @@ -22,6 +22,8 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.StubMvcResult; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * Unit tests for {@link JsonPathResultMatchers}. * @@ -57,9 +59,10 @@ public class JsonPathResultMatchersTests { } } - @Test(expected = AssertionError.class) + @Test public void valueWithMismatch() throws Exception { - new JsonPathResultMatchers("$.str").value("bogus").match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").value("bogus").match(stubMvcResult)); } @Test @@ -82,9 +85,10 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.num").value(Matchers.equalTo(5.0f), Float.class).match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void valueWithMatcherAndMismatch() throws Exception { - new JsonPathResultMatchers("$.str").value(Matchers.equalTo("bogus")).match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").value(Matchers.equalTo("bogus")).match(stubMvcResult)); } @Test @@ -102,9 +106,10 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.emptyMap").exists().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void existsNoMatch() throws Exception { - new JsonPathResultMatchers("$.bogus").exists().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.bogus").exists().match(stubMvcResult)); } @Test @@ -112,19 +117,22 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.bogus").doesNotExist().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistNoMatch() throws Exception { - new JsonPathResultMatchers("$.str").doesNotExist().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").doesNotExist().match(stubMvcResult)); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistForAnEmptyArray() throws Exception { - new JsonPathResultMatchers("$.emptyArray").doesNotExist().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.emptyArray").doesNotExist().match(stubMvcResult)); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistForAnEmptyMap() throws Exception { - new JsonPathResultMatchers("$.emptyMap").doesNotExist().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.emptyMap").doesNotExist().match(stubMvcResult)); } @Test @@ -167,19 +175,22 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.colorMap").isNotEmpty().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void isNotEmptyForAnEmptyString() throws Exception { - new JsonPathResultMatchers("$.emptyString").isNotEmpty().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.emptyString").isNotEmpty().match(stubMvcResult)); } - @Test(expected = AssertionError.class) + @Test public void isNotEmptyForAnEmptyArray() throws Exception { - new JsonPathResultMatchers("$.emptyArray").isNotEmpty().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.emptyArray").isNotEmpty().match(stubMvcResult)); } - @Test(expected = AssertionError.class) + @Test public void isNotEmptyForAnEmptyMap() throws Exception { - new JsonPathResultMatchers("$.emptyMap").isNotEmpty().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.emptyMap").isNotEmpty().match(stubMvcResult)); } @Test @@ -192,9 +203,10 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.emptyArray").isArray().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void isArrayNoMatch() throws Exception { - new JsonPathResultMatchers("$.bar").isArray().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.bar").isArray().match(stubMvcResult)); } @Test @@ -207,9 +219,10 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.emptyMap").isMap().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void isMapNoMatch() throws Exception { - new JsonPathResultMatchers("$.str").isMap().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").isMap().match(stubMvcResult)); } @Test @@ -217,9 +230,10 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.bool").isBoolean().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void isBooleanNoMatch() throws Exception { - new JsonPathResultMatchers("$.str").isBoolean().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").isBoolean().match(stubMvcResult)); } @Test @@ -227,9 +241,10 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.num").isNumber().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void isNumberNoMatch() throws Exception { - new JsonPathResultMatchers("$.str").isNumber().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").isNumber().match(stubMvcResult)); } @Test @@ -237,23 +252,26 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.str").isString().match(stubMvcResult); } - @Test(expected = AssertionError.class) + @Test public void isStringNoMatch() throws Exception { - new JsonPathResultMatchers("$.arr").isString().match(stubMvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.arr").isString().match(stubMvcResult)); } - @Test(expected = AssertionError.class) + @Test public void valueWithJsonPrefixNotConfigured() throws Exception { String jsonPrefix = "prefix"; StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix); - new JsonPathResultMatchers("$.str").value("foo").match(result); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").value("foo").match(result)); } - @Test(expected = AssertionError.class) + @Test public void valueWithJsonWrongPrefix() throws Exception { String jsonPrefix = "prefix"; StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix); - new JsonPathResultMatchers("$.str").prefix("wrong").value("foo").match(result); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").prefix("wrong").value("foo").match(result)); } @Test @@ -263,14 +281,15 @@ public class JsonPathResultMatchersTests { new JsonPathResultMatchers("$.str").prefix(jsonPrefix).value("foo").match(result); } - @Test(expected = AssertionError.class) + @Test public void prefixWithPayloadNotLongEnough() throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); response.addHeader("Content-Type", "application/json"); response.getWriter().print(new String("test".getBytes("ISO-8859-1"))); StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response); - new JsonPathResultMatchers("$.str").prefix("prefix").value("foo").match(result); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new JsonPathResultMatchers("$.str").prefix("prefix").value("foo").match(result)); } private StubMvcResult createPrefixedStubMvcResult(String jsonPrefix) throws Exception { diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/MockMvcResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/MockMvcResultMatchersTests.java index 382f7e89b77..688ad49f977 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/MockMvcResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/MockMvcResultMatchersTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.StubMvcResult; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlPattern; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlTemplate; @@ -51,9 +52,10 @@ public class MockMvcResultMatchersTests { redirectedUrlPattern("/resource/*").match(getRedirectedUrlStubMvcResult("/resource/1")); } - @Test(expected = AssertionError.class) + @Test public void redirectWithNonMatchingPattern() throws Exception { - redirectedUrlPattern("/resource/").match(getRedirectedUrlStubMvcResult("/resource/1")); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + redirectedUrlPattern("/resource/").match(getRedirectedUrlStubMvcResult("/resource/1"))); } @Test @@ -76,9 +78,10 @@ public class MockMvcResultMatchersTests { forwardedUrlPattern("/api/**/?").match(getForwardedUrlStubMvcResult("/api/resource/1")); } - @Test(expected = AssertionError.class) + @Test public void forwardWithNonMatchingPattern() throws Exception { - forwardedUrlPattern("/resource/").match(getForwardedUrlStubMvcResult("/resource/1")); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + forwardedUrlPattern("/resource/").match(getForwardedUrlStubMvcResult("/resource/1"))); } private StubMvcResult getRedirectedUrlStubMvcResult(String redirectUrl) throws Exception { 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 f77e67ae1a8..0a063deea26 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 @@ -27,6 +27,7 @@ import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.ModelAndView; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; @@ -69,9 +70,10 @@ public class ModelResultMatchersTests { this.matchers.attributeExists("good").match(this.mvcResult); } - @Test(expected = AssertionError.class) + @Test public void attributeExists_doesNotExist() throws Exception { - this.matchers.attributeExists("bad").match(this.mvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeExists("bad").match(this.mvcResult)); } @Test @@ -79,9 +81,10 @@ public class ModelResultMatchersTests { this.matchers.attributeDoesNotExist("bad").match(this.mvcResult); } - @Test(expected = AssertionError.class) + @Test public void attributeDoesNotExist_doesExist() throws Exception { - this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError)); } @Test @@ -89,9 +92,10 @@ public class ModelResultMatchersTests { this.matchers.attribute("good", is("good")).match(this.mvcResult); } - @Test(expected = AssertionError.class) + @Test public void attribute_notEqual() throws Exception { - this.matchers.attribute("good", is("bad")).match(this.mvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attribute("good", is("bad")).match(this.mvcResult)); } @Test @@ -99,9 +103,10 @@ public class ModelResultMatchersTests { this.matchers.hasNoErrors().match(this.mvcResult); } - @Test(expected = AssertionError.class) + @Test public void hasNoErrors_withErrors() throws Exception { - this.matchers.hasNoErrors().match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.hasNoErrors().match(this.mvcResultWithError)); } @Test @@ -109,9 +114,10 @@ public class ModelResultMatchersTests { this.matchers.attributeHasErrors("date").match(this.mvcResultWithError); } - @Test(expected = AssertionError.class) + @Test public void attributeHasErrors_withoutErrors() throws Exception { - this.matchers.attributeHasErrors("good").match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasErrors("good").match(this.mvcResultWithError)); } @Test @@ -119,14 +125,16 @@ public class ModelResultMatchersTests { this.matchers.attributeHasNoErrors("good").match(this.mvcResult); } - @Test(expected = AssertionError.class) + @Test public void attributeHasNoErrors_withoutAttribute() throws Exception { - this.matchers.attributeHasNoErrors("missing").match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasNoErrors("missing").match(this.mvcResultWithError)); } - @Test(expected = AssertionError.class) + @Test public void attributeHasNoErrors_withErrors() throws Exception { - this.matchers.attributeHasNoErrors("date").match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasNoErrors("date").match(this.mvcResultWithError)); } @Test @@ -134,19 +142,22 @@ public class ModelResultMatchersTests { this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResultWithError); } - @Test(expected = AssertionError.class) + @Test public void attributeHasFieldErrors_withoutAttribute() throws Exception { - this.matchers.attributeHasFieldErrors("missing", "bad").match(this.mvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasFieldErrors("missing", "bad").match(this.mvcResult)); } - @Test(expected = AssertionError.class) + @Test public void attributeHasFieldErrors_withoutErrorsForAttribute() throws Exception { - this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResult); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResult)); } - @Test(expected = AssertionError.class) + @Test public void attributeHasFieldErrors_withoutErrorsForField() throws Exception { - this.matchers.attributeHasFieldErrors("date", "good", "time").match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasFieldErrors("date", "good", "time").match(this.mvcResultWithError)); } @Test @@ -154,9 +165,10 @@ public class ModelResultMatchersTests { this.matchers.attributeHasFieldErrorCode("date", "time", "error").match(this.mvcResultWithError); } - @Test(expected = AssertionError.class) + @Test public void attributeHasFieldErrorCode_withoutErrorOnField() throws Exception { - this.matchers.attributeHasFieldErrorCode("date", "time", "incorrectError").match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasFieldErrorCode("date", "time", "incorrectError").match(this.mvcResultWithError)); } @Test @@ -164,9 +176,10 @@ public class ModelResultMatchersTests { this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("err")).match(this.mvcResultWithError); } - @Test(expected = AssertionError.class) + @Test public void attributeHasFieldErrorCode_startsWith_withoutErrorOnField() throws Exception { - this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("inc")).match(this.mvcResultWithError); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("inc")).match(this.mvcResultWithError)); } private MvcResult getMvcResult(ModelAndView modelAndView) { diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java index ed0624f59a9..20cb7ca8bc0 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 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. @@ -25,6 +25,8 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.StubMvcResult; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * Tests for {@link XpathResultMatchers}. * @@ -40,9 +42,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void nodeNoMatch() throws Exception { - new XpathResultMatchers("/foo/bar", null).node(Matchers.nullValue()).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/bar", null).node(Matchers.nullValue()).match(getStubMvcResult())); } @Test @@ -50,9 +53,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/bar", null).exists().match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void existsNoMatch() throws Exception { - new XpathResultMatchers("/foo/Bar", null).exists().match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/Bar", null).exists().match(getStubMvcResult())); } @Test @@ -60,9 +64,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/Bar", null).doesNotExist().match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void doesNotExistNoMatch() throws Exception { - new XpathResultMatchers("/foo/bar", null).doesNotExist().match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/bar", null).doesNotExist().match(getStubMvcResult())); } @Test @@ -70,9 +75,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/bar", null).nodeCount(2).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void nodeCountNoMatch() throws Exception { - new XpathResultMatchers("/foo/bar", null).nodeCount(1).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/bar", null).nodeCount(1).match(getStubMvcResult())); } @Test @@ -80,9 +86,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/bar[1]", null).string("111").match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void stringNoMatch() throws Exception { - new XpathResultMatchers("/foo/bar[1]", null).string("112").match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/bar[1]", null).string("112").match(getStubMvcResult())); } @Test @@ -90,9 +97,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/bar[1]", null).number(111.0).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void numberNoMatch() throws Exception { - new XpathResultMatchers("/foo/bar[1]", null).number(111.1).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/bar[1]", null).number(111.1).match(getStubMvcResult())); } @Test @@ -100,9 +108,10 @@ public class XpathResultMatchersTests { new XpathResultMatchers("/foo/bar[2]", null).booleanValue(true).match(getStubMvcResult()); } - @Test(expected = AssertionError.class) + @Test public void booleanValueNoMatch() throws Exception { - new XpathResultMatchers("/foo/bar[2]", null).booleanValue(false).match(getStubMvcResult()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + new XpathResultMatchers("/foo/bar[2]", null).booleanValue(false).match(getStubMvcResult())); } @Test 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 6d0f7118b1d..6a32a3afc4a 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java @@ -34,6 +34,7 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.request.WebRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; @@ -158,9 +159,10 @@ public class HeaderAssertionTests { this.mockMvc.perform(get("/persons/1")).andExpect(header().exists(LAST_MODIFIED)); } - @Test(expected = AssertionError.class) + @Test public void existsFail() throws Exception { - this.mockMvc.perform(get("/persons/1")).andExpect(header().exists("X-Custom-Header")); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.mockMvc.perform(get("/persons/1")).andExpect(header().exists("X-Custom-Header"))); } @Test // SPR-10771 @@ -168,14 +170,16 @@ public class HeaderAssertionTests { this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist("X-Custom-Header")); } - @Test(expected = AssertionError.class) // SPR-10771 + @Test // SPR-10771 public void doesNotExistFail() throws Exception { - this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist(LAST_MODIFIED)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist(LAST_MODIFIED))); } - @Test(expected = AssertionError.class) + @Test public void longValueWithIncorrectResponseHeaderValue() throws Exception { - this.mockMvc.perform(get("/persons/1")).andExpect(header().longValue("X-Rate-Limiting", 1)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> + this.mockMvc.perform(get("/persons/1")).andExpect(header().longValue("X-Rate-Limiting", 1))); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java index 0b5607ec318..4dbe0f610e2 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java @@ -38,6 +38,7 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -92,28 +93,32 @@ public class StandaloneMockMvcBuilderTests { assertEquals(wac, WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext())); } - @Test(expected = IllegalArgumentException.class) + @Test public void addFiltersFiltersNull() { StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController()); - builder.addFilters((Filter[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + builder.addFilters((Filter[]) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void addFiltersFiltersContainsNull() { StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController()); - builder.addFilters(new ContinueFilter(), (Filter) null); + assertThatIllegalArgumentException().isThrownBy(() -> + builder.addFilters(new ContinueFilter(), (Filter) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void addFilterPatternsNull() { StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController()); - builder.addFilter(new ContinueFilter(), (String[]) null); + assertThatIllegalArgumentException().isThrownBy(() -> + builder.addFilter(new ContinueFilter(), (String[]) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void addFilterPatternContainsNull() { StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController()); - builder.addFilter(new ContinueFilter(), (String) null); + assertThatIllegalArgumentException().isThrownBy(() -> + builder.addFilter(new ContinueFilter(), (String) null)); } @Test // SPR-13375 diff --git a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java index 60d5872914b..014c485d1bc 100644 --- a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java @@ -31,8 +31,7 @@ import org.springframework.dao.support.DataAccessUtilsTests.MapPersistenceExcept import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.stereotype.Repository; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for PersistenceExceptionTranslationAdvisor's exception translation, as applied by @@ -69,20 +68,12 @@ public class PersistenceExceptionTranslationAdvisorTests { ri.throwsPersistenceException(); target.setBehavior(persistenceException1); - try { - ri.noThrowsClause(); - fail(); - } - catch (RuntimeException ex) { - assertSame(persistenceException1, ex); - } - try { - ri.throwsPersistenceException(); - fail(); - } - catch (RuntimeException ex) { - assertSame(persistenceException1, ex); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + ri::noThrowsClause) + .isSameAs(persistenceException1); + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + ri::throwsPersistenceException) + .isSameAs(persistenceException1); } @Test @@ -94,20 +85,12 @@ public class PersistenceExceptionTranslationAdvisorTests { ri.throwsPersistenceException(); target.setBehavior(doNotTranslate); - try { - ri.noThrowsClause(); - fail(); - } - catch (RuntimeException ex) { - assertSame(doNotTranslate, ex); - } - try { - ri.throwsPersistenceException(); - fail(); - } - catch (RuntimeException ex) { - assertSame(doNotTranslate, ex); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + ri::noThrowsClause) + .isSameAs(doNotTranslate); + assertThatExceptionOfType(RuntimeException.class).isThrownBy( + ri::throwsPersistenceException) + .isSameAs(doNotTranslate); } @Test @@ -139,25 +122,13 @@ public class PersistenceExceptionTranslationAdvisorTests { RepositoryInterface ri = createProxy(target); target.setBehavior(persistenceException1); - try { - ri.noThrowsClause(); - fail(); - } - catch (DataAccessException ex) { - // Expected - assertSame(persistenceException1, ex.getCause()); - } - catch (PersistenceException ex) { - fail("Should have been translated"); - } + assertThatExceptionOfType(DataAccessException.class).isThrownBy( + ri::noThrowsClause) + .withCause(persistenceException1); - try { - ri.throwsPersistenceException(); - fail(); - } - catch (PersistenceException ex) { - assertSame(persistenceException1, ex); - } + assertThatExceptionOfType(PersistenceException.class).isThrownBy( + ri::throwsPersistenceException) + .isSameAs(persistenceException1); } diff --git a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java index d8de0a6a979..15014bc2172 100644 --- a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java @@ -23,7 +23,6 @@ import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.junit.Test; -import org.springframework.aop.Advisor; import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; @@ -38,10 +37,10 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.stereotype.Repository; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -80,24 +79,15 @@ public class PersistenceExceptionTranslationPostProcessorTests { assertTrue(AopUtils.isAopProxy(rwi2)); rwi2.additionalMethod(false); checkWillTranslateExceptions(rwi2); - try { - rwi2.additionalMethod(true); - fail("Should have thrown DataAccessResourceFailureException"); - } - catch (DataAccessResourceFailureException ex) { - assertEquals("my failure", ex.getMessage()); - } + assertThatExceptionOfType(DataAccessResourceFailureException.class).isThrownBy(() -> + rwi2.additionalMethod(true)) + .withMessage("my failure"); } protected void checkWillTranslateExceptions(Object o) { - assertTrue(o instanceof Advised); - Advised a = (Advised) o; - for (Advisor advisor : a.getAdvisors()) { - if (advisor instanceof PersistenceExceptionTranslationAdvisor) { - return; - } - } - fail("No translation"); + assertThat(o).isInstanceOf(Advised.class); + assertThat(((Advised) o).getAdvisors()).anyMatch( + PersistenceExceptionTranslationAdvisor.class::isInstance); } diff --git a/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java b/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java index a72488b0da8..9d91a21304c 100644 --- a/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java @@ -22,6 +22,7 @@ import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.function.Consumer; import org.junit.Test; @@ -30,10 +31,11 @@ import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.TypeMismatchDataAccessException; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -47,45 +49,21 @@ public class DataAccessUtilsTests { assertNull(DataAccessUtils.uniqueResult(col)); - try { - DataAccessUtils.requiredUniqueResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(0, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.requiredUniqueResult(col)) + .satisfies(sizeRequirements(1, 0)); - try { - DataAccessUtils.objectResult(col, String.class); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(0, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.objectResult(col, String.class)) + .satisfies(sizeRequirements(1, 0)); - try { - DataAccessUtils.intResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(0, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.intResult(col)) + .satisfies(sizeRequirements(1, 0)); - try { - DataAccessUtils.longResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(0, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.longResult(col)) + .satisfies(sizeRequirements(1, 0)); } @Test @@ -94,55 +72,25 @@ public class DataAccessUtilsTests { col.add("test1"); col.add("test2"); - try { - DataAccessUtils.uniqueResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(2, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.uniqueResult(col)) + .satisfies(sizeRequirements(1, 2)); - try { - DataAccessUtils.requiredUniqueResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(2, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.requiredUniqueResult(col)) + .satisfies(sizeRequirements(1, 2)); - try { - DataAccessUtils.objectResult(col, String.class); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(2, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.objectResult(col, String.class)) + .satisfies(sizeRequirements(1, 2)); - try { - DataAccessUtils.intResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(2, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.intResult(col)) + .satisfies(sizeRequirements(1, 2)); - try { - DataAccessUtils.longResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(2, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.longResult(col)) + .satisfies(sizeRequirements(1, 2)); } @Test @@ -180,15 +128,9 @@ public class DataAccessUtilsTests { col.add(new Integer(5)); col.add(new Integer(5)); - try { - DataAccessUtils.uniqueResult(col); - fail("Should have thrown IncorrectResultSizeDataAccessException"); - } - catch (IncorrectResultSizeDataAccessException ex) { - // expected - assertEquals(1, ex.getExpectedSize()); - assertEquals(2, ex.getActualSize()); - } + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> + DataAccessUtils.uniqueResult(col)) + .satisfies(sizeRequirements(1, 2)); } @Test @@ -213,21 +155,11 @@ public class DataAccessUtilsTests { assertEquals("test1", DataAccessUtils.requiredUniqueResult(col)); assertEquals("test1", DataAccessUtils.objectResult(col, String.class)); - try { - DataAccessUtils.intResult(col); - fail("Should have thrown TypeMismatchDataAccessException"); - } - catch (TypeMismatchDataAccessException ex) { - // expected - } + assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> + DataAccessUtils.intResult(col)); - try { - DataAccessUtils.longResult(col); - fail("Should have thrown TypeMismatchDataAccessException"); - } - catch (TypeMismatchDataAccessException ex) { - // expected - } + assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> + DataAccessUtils.longResult(col)); } @Test @@ -241,21 +173,11 @@ public class DataAccessUtilsTests { assertEquals(date, DataAccessUtils.objectResult(col, Date.class)); assertEquals(date.toString(), DataAccessUtils.objectResult(col, String.class)); - try { - DataAccessUtils.intResult(col); - fail("Should have thrown TypeMismatchDataAccessException"); - } - catch (TypeMismatchDataAccessException ex) { - // expected - } + assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> + DataAccessUtils.intResult(col)); - try { - DataAccessUtils.longResult(col); - fail("Should have thrown TypeMismatchDataAccessException"); - } - catch (TypeMismatchDataAccessException ex) { - // expected - } + assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> + DataAccessUtils.longResult(col)); } @Test @@ -274,6 +196,13 @@ public class DataAccessUtilsTests { assertSame(out, DataAccessUtils.translateIfNecessary(in, mpet)); } + private Consumer sizeRequirements( + int expectedSize, int actualSize) { + return ex -> { + assertThat(ex.getExpectedSize()).as("expected size").isEqualTo(expectedSize); + assertThat(ex.getActualSize()).as("actual size").isEqualTo(actualSize); + }; + } public static class MapPersistenceExceptionTranslator implements PersistenceExceptionTranslator { diff --git a/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java b/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java index edf31663f35..dee1eaf8b7d 100644 --- a/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java @@ -21,6 +21,7 @@ import javax.resource.spi.ManagedConnectionFactory; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -36,9 +37,10 @@ import static org.mockito.Mockito.verify; */ public class LocalConnectionFactoryBeanTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testManagedConnectionFactoryIsRequired() throws Exception { - new LocalConnectionFactoryBean().afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + new LocalConnectionFactoryBean()::afterPropertiesSet); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java index 9893132cdbb..09d23a9c7e3 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java @@ -39,6 +39,9 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -273,7 +276,7 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { @@ -281,12 +284,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(synch); throw new IllegalStateException("I want a rollback"); } - }); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); verify(ut).setRollbackOnly(); @@ -305,19 +303,14 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); TransactionSynchronizationManager.registerSynchronization(synch); } - }); - fail("Should have thrown OptimisticLockingFailureException"); - } - catch (OptimisticLockingFailureException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); verify(ut).setRollbackOnly(); @@ -361,7 +354,7 @@ public class JtaTransactionManagerTests { ptm.setGlobalRollbackOnParticipationFailure(false); TransactionTemplate tt = new TransactionTemplate(ptm); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { @@ -369,12 +362,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(synch); throw new IllegalStateException("I want a rollback"); } - }); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); verify(synch).beforeCompletion(); @@ -705,18 +693,13 @@ public class JtaTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); } - }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } @@ -733,18 +716,13 @@ public class JtaTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { - tt.execute(new TransactionCallbackWithoutResult() { + assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> + tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); } - }); - fail("Should have thrown CannotCreateTransactionException"); - } - catch (CannotCreateTransactionException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); verify(tm).resume(tx); } @@ -782,17 +760,12 @@ public class JtaTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { + assertThatExceptionOfType(TransactionSuspensionNotSupportedException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { } - }); - fail("Should have thrown TransactionSuspensionNotSupportedException"); - } - catch (TransactionSuspensionNotSupportedException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } @@ -801,7 +774,7 @@ public class JtaTransactionManagerTests { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); - try { + assertThatExceptionOfType(InvalidIsolationLevelException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); @@ -811,11 +784,7 @@ public class JtaTransactionManagerTests { // something transactional } }); - fail("Should have thrown InvalidIsolationLevelException"); - } - catch (InvalidIsolationLevelException ex) { - // expected - } + }); } @Test @@ -823,7 +792,7 @@ public class JtaTransactionManagerTests { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willThrow(new SystemException("system exception")); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -832,11 +801,7 @@ public class JtaTransactionManagerTests { // something transactional } }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + }); } @Test @@ -864,7 +829,7 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new NotSupportedException("not supported")).given(ut).begin(); - try { + assertThatExceptionOfType(NestedTransactionNotSupportedException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); @@ -874,11 +839,7 @@ public class JtaTransactionManagerTests { // something transactional } }); - fail("Should have thrown NestedTransactionNotSupportedException"); - } - catch (NestedTransactionNotSupportedException ex) { - // expected - } + }); } @Test @@ -887,7 +848,7 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new UnsupportedOperationException("not supported")).given(ut).begin(); - try { + assertThatExceptionOfType(NestedTransactionNotSupportedException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); @@ -897,11 +858,7 @@ public class JtaTransactionManagerTests { // something transactional } }); - fail("Should have thrown NestedTransactionNotSupportedException"); - } - catch (NestedTransactionNotSupportedException ex) { - // expected - } + }); } @Test @@ -910,7 +867,7 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); willThrow(new SystemException("system exception")).given(ut).begin(); - try { + assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -919,11 +876,7 @@ public class JtaTransactionManagerTests { // something transactional } }); - fail("Should have thrown CannotCreateTransactionException"); - } - catch (CannotCreateTransactionException ex) { - // expected - } + }); } @Test @@ -933,7 +886,7 @@ public class JtaTransactionManagerTests { Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); willThrow(new RollbackException("unexpected rollback")).given(ut).commit(); - try { + assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -948,11 +901,7 @@ public class JtaTransactionManagerTests { }); } }); - fail("Should have thrown UnexpectedRollbackException"); - } - catch (UnexpectedRollbackException ex) { - // expected - } + }); verify(ut).begin(); } @@ -1007,12 +956,7 @@ public class JtaTransactionManagerTests { if (!outerTransactionBoundaryReached) { tm.rollback(ts); } - if (failEarly) { - assertFalse(outerTransactionBoundaryReached); - } - else { - assertTrue(outerTransactionBoundaryReached); - } + assertThat(outerTransactionBoundaryReached).isNotEqualTo(failEarly); } verify(ut).begin(); @@ -1031,7 +975,7 @@ public class JtaTransactionManagerTests { Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); willThrow(new HeuristicMixedException("heuristic exception")).given(ut).commit(); - try { + assertThatExceptionOfType(HeuristicCompletionException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -1046,12 +990,7 @@ public class JtaTransactionManagerTests { }); } }); - fail("Should have thrown HeuristicCompletionException"); - } - catch (HeuristicCompletionException ex) { - // expected - assertTrue(ex.getOutcomeState() == HeuristicCompletionException.STATE_MIXED); - } + }).satisfies(ex -> assertThat(ex.getOutcomeState()).isEqualTo(HeuristicCompletionException.STATE_MIXED)); verify(ut).begin(); } @@ -1063,7 +1002,7 @@ public class JtaTransactionManagerTests { Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); willThrow(new HeuristicRollbackException("heuristic exception")).given(ut).commit(); - try { + assertThatExceptionOfType(HeuristicCompletionException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -1078,12 +1017,7 @@ public class JtaTransactionManagerTests { }); } }); - fail("Should have thrown HeuristicCompletionException"); - } - catch (HeuristicCompletionException ex) { - // expected - assertTrue(ex.getOutcomeState() == HeuristicCompletionException.STATE_ROLLED_BACK); - } + }).satisfies(ex -> assertThat(ex.getOutcomeState()).isEqualTo(HeuristicCompletionException.STATE_ROLLED_BACK)); verify(ut).begin(); } @@ -1095,7 +1029,7 @@ public class JtaTransactionManagerTests { Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); willThrow(new SystemException("system exception")).given(ut).commit(); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -1110,11 +1044,7 @@ public class JtaTransactionManagerTests { }); } }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + }); verify(ut).begin(); } @@ -1125,7 +1055,7 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); willThrow(new SystemException("system exception")).given(ut).rollback(); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -1140,11 +1070,7 @@ public class JtaTransactionManagerTests { status.setRollbackOnly(); } }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + }); verify(ut).begin(); } @@ -1155,7 +1081,7 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly(); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -1164,11 +1090,7 @@ public class JtaTransactionManagerTests { status.setRollbackOnly(); } }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + }); } @Test @@ -1177,7 +1099,7 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new SystemException("system exception")).given(ut).setRollbackOnly(); - try { + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.execute(new TransactionCallbackWithoutResult() { @@ -1192,11 +1114,7 @@ public class JtaTransactionManagerTests { }); } }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - } + }); } @Test @@ -1212,15 +1130,9 @@ public class JtaTransactionManagerTests { // first commit ptm.commit(status); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { - // second commit attempt - ptm.commit(status); - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } - + // second commit attempt + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> + ptm.commit(status)); verify(ut).begin(); verify(ut).commit(); } @@ -1237,14 +1149,9 @@ public class JtaTransactionManagerTests { // first rollback ptm.rollback(status); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { - // second rollback attempt - ptm.rollback(status); - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } + // second rollback attempt + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> + ptm.rollback(status)); verify(ut).begin(); verify(ut).rollback(); @@ -1262,14 +1169,9 @@ public class JtaTransactionManagerTests { // first: rollback ptm.rollback(status); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - try { - // second: commit attempt - ptm.commit(status); - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } + // second: commit attempt + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> + ptm.commit(status)); verify(ut).begin(); verify(ut).rollback(); diff --git a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java index d3dd12722d9..0678892d5f7 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java @@ -25,12 +25,13 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -50,13 +51,8 @@ public class TransactionSupportTests { assertTrue("Must have transaction", status2.hasTransaction()); assertTrue("Must be new transaction", status2.isNewTransaction()); - try { - tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)); - fail("Should not have thrown NoTransactionException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> + tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY))); } @Test @@ -72,15 +68,10 @@ public class TransactionSupportTests { assertTrue("Must have transaction", status2.getTransaction() != null); assertTrue("Must not be new transaction", !status2.isNewTransaction()); - try { - DefaultTransactionStatus status3 = (DefaultTransactionStatus) - tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)); - assertTrue("Must have transaction", status3.getTransaction() != null); - assertTrue("Must not be new transaction", !status3.isNewTransaction()); - } - catch (NoTransactionException ex) { - fail("Should not have thrown NoTransactionException"); - } + DefaultTransactionStatus status3 = (DefaultTransactionStatus) + tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)); + assertTrue("Must have transaction", status3.getTransaction() != null); + assertTrue("Must not be new transaction", !status3.isNewTransaction()); } @Test @@ -91,8 +82,8 @@ public class TransactionSupportTests { assertTrue("triggered begin", tm.begin); assertTrue("triggered commit", tm.commit); - assertTrue("no rollback", !tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); + assertFalse("no rollback", tm.rollback); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test @@ -102,9 +93,9 @@ public class TransactionSupportTests { tm.rollback(status); assertTrue("triggered begin", tm.begin); - assertTrue("no commit", !tm.commit); + assertFalse("no commit", tm.commit); assertTrue("triggered rollback", tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test @@ -115,9 +106,9 @@ public class TransactionSupportTests { tm.commit(status); assertTrue("triggered begin", tm.begin); - assertTrue("no commit", !tm.commit); + assertFalse("no commit", tm.commit); assertTrue("triggered rollback", tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test @@ -126,10 +117,10 @@ public class TransactionSupportTests { TransactionStatus status = tm.getTransaction(null); tm.commit(status); - assertTrue("no begin", !tm.begin); - assertTrue("no commit", !tm.commit); - assertTrue("no rollback", !tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); + assertFalse("no begin", tm.begin); + assertFalse("no commit", tm.commit); + assertFalse("no rollback", tm.rollback); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test @@ -138,9 +129,9 @@ public class TransactionSupportTests { TransactionStatus status = tm.getTransaction(null); tm.rollback(status); - assertTrue("no begin", !tm.begin); - assertTrue("no commit", !tm.commit); - assertTrue("no rollback", !tm.rollback); + assertFalse("no begin", tm.begin); + assertFalse("no commit", tm.commit); + assertFalse("no rollback", tm.rollback); assertTrue("triggered rollbackOnly", tm.rollbackOnly); } @@ -151,9 +142,9 @@ public class TransactionSupportTests { status.setRollbackOnly(); tm.commit(status); - assertTrue("no begin", !tm.begin); - assertTrue("no commit", !tm.commit); - assertTrue("no rollback", !tm.rollback); + assertFalse("no begin", tm.begin); + assertFalse("no commit", tm.commit); + assertFalse("no rollback", tm.rollback); assertTrue("triggered rollbackOnly", tm.rollbackOnly); } @@ -169,8 +160,8 @@ public class TransactionSupportTests { assertTrue("triggered begin", tm.begin); assertTrue("triggered commit", tm.commit); - assertTrue("no rollback", !tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); + assertFalse("no rollback", tm.rollback); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test @@ -192,23 +183,18 @@ public class TransactionSupportTests { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); final RuntimeException ex = new RuntimeException("Some application exception"); - try { - template.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - throw ex; - } - }); - fail("Should have propagated RuntimeException"); - } - catch (RuntimeException caught) { - // expected - assertTrue("Correct exception", caught == ex); - assertTrue("triggered begin", tm.begin); - assertTrue("no commit", !tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + template.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + throw ex; + } + })) + .isSameAs(ex); + assertTrue("triggered begin", tm.begin); + assertFalse("no commit", tm.commit); + assertTrue("triggered rollback", tm.rollback); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @SuppressWarnings("serial") @@ -224,45 +210,35 @@ public class TransactionSupportTests { }; TransactionTemplate template = new TransactionTemplate(tm); final RuntimeException ex = new RuntimeException("Some application exception"); - try { - template.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - throw ex; - } - }); - fail("Should have propagated RuntimeException"); - } - catch (RuntimeException caught) { - // expected - assertTrue("Correct exception", caught == tex); - assertTrue("triggered begin", tm.begin); - assertTrue("no commit", !tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + template.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + throw ex; + } + })) + .isSameAs(tex); + assertTrue("triggered begin", tm.begin); + assertFalse("no commit", tm.commit); + assertTrue("triggered rollback", tm.rollback); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test public void transactionTemplateWithError() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); - try { - template.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - throw new Error("Some application error"); - } - }); - fail("Should have propagated Error"); - } - catch (Error err) { - // expected - assertTrue("triggered begin", tm.begin); - assertTrue("no commit", !tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertTrue("no rollbackOnly", !tm.rollbackOnly); - } + assertThatExceptionOfType(Error.class).isThrownBy(() -> + template.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + throw new Error("Some application error"); + } + })); + assertTrue("triggered begin", tm.begin); + assertFalse("no commit", tm.commit); + assertTrue("triggered rollback", tm.rollback); + assertFalse("no rollbackOnly", tm.rollbackOnly); } @Test @@ -272,43 +248,24 @@ public class TransactionSupportTests { template.setTransactionManager(tm); assertTrue("correct transaction manager set", template.getTransactionManager() == tm); - try { - template.setPropagationBehaviorName("TIMEOUT_DEFAULT"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + template.setPropagationBehaviorName("TIMEOUT_DEFAULT")); template.setPropagationBehaviorName("PROPAGATION_SUPPORTS"); assertTrue("Correct propagation behavior set", template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_SUPPORTS); - try { - template.setPropagationBehavior(999); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + template.setPropagationBehavior(999)); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY); assertTrue("Correct propagation behavior set", template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY); - try { - template.setIsolationLevelName("TIMEOUT_DEFAULT"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + template.setIsolationLevelName("TIMEOUT_DEFAULT")); template.setIsolationLevelName("ISOLATION_SERIALIZABLE"); assertTrue("Correct isolation level set", template.getIsolationLevel() == TransactionDefinition.ISOLATION_SERIALIZABLE); - try { - template.setIsolationLevel(999); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(() -> + template.setIsolationLevel(999)); + template.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); assertTrue("Correct isolation level set", template.getIsolationLevel() == TransactionDefinition.ISOLATION_REPEATABLE_READ); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java index 06188c67abd..03005d67546 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java @@ -30,10 +30,10 @@ import org.springframework.transaction.interceptor.TransactionAttribute; import org.springframework.transaction.interceptor.TransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionInterceptor; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -79,14 +79,10 @@ public class TxNamespaceHandlerTests { assertEquals("Should not have started another transaction", 1, ptm.begun); // try with exceptional - try { - testBean.exceptional(new IllegalArgumentException("foo")); - fail("Should NEVER get here"); - } - catch (Throwable throwable) { - assertEquals("Should have another started transaction", 2, ptm.begun); - assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + testBean.exceptional(new IllegalArgumentException("foo"))); + assertEquals("Should have another started transaction", 2, ptm.begun); + assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java index 2338bcd64d4..08813ed3074 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java @@ -24,10 +24,12 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -134,21 +136,13 @@ public class AnnotationTransactionInterceptorTests { TestWithExceptions proxy = (TestWithExceptions) proxyFactory.getProxy(); - try { - proxy.doSomethingErroneous(); - fail("Should throw IllegalStateException"); - } - catch (IllegalStateException ex) { - assertGetTransactionAndRollbackCount(1); - } + assertThatIllegalStateException().isThrownBy( + proxy::doSomethingErroneous) + .satisfies(ex -> assertGetTransactionAndRollbackCount(1)); - try { - proxy.doSomethingElseErroneous(); - fail("Should throw IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - assertGetTransactionAndRollbackCount(2); - } + assertThatIllegalArgumentException().isThrownBy( + proxy::doSomethingElseErroneous) + .satisfies(ex -> assertGetTransactionAndRollbackCount(2)); } @Test @@ -159,13 +153,9 @@ public class AnnotationTransactionInterceptorTests { TestWithExceptions proxy = (TestWithExceptions) proxyFactory.getProxy(); - try { - proxy.doSomethingElseWithCheckedException(); - fail("Should throw Exception"); - } - catch (Exception ex) { - assertGetTransactionAndCommitCount(1); - } + assertThatExceptionOfType(Exception.class).isThrownBy( + proxy::doSomethingElseWithCheckedException) + .satisfies(ex -> assertGetTransactionAndCommitCount(1)); } @Test @@ -176,13 +166,9 @@ public class AnnotationTransactionInterceptorTests { TestWithExceptions proxy = (TestWithExceptions) proxyFactory.getProxy(); - try { - proxy.doSomethingElseWithCheckedExceptionAndRollbackRule(); - fail("Should throw Exception"); - } - catch (Exception ex) { - assertGetTransactionAndRollbackCount(1); - } + assertThatExceptionOfType(Exception.class).isThrownBy( + proxy::doSomethingElseWithCheckedExceptionAndRollbackRule) + .satisfies(ex -> assertGetTransactionAndRollbackCount(1)); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java index 5bcb4e19956..8d6d0dacc61 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java @@ -35,9 +35,9 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.config.TransactionManagementConfigUtils; import org.springframework.transaction.event.TransactionalEventListenerFactory; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -78,14 +78,12 @@ public class AnnotationTransactionNamespaceHandlerTests { assertEquals("Should not have started another transaction", 1, ptm.begun); // try with exceptional - try { - testBean.exceptional(new IllegalArgumentException("foo")); - fail("Should NEVER get here"); - } - catch (Throwable throwable) { - assertEquals("Should have another started transaction", 2, ptm.begun); - assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + testBean.exceptional(new IllegalArgumentException("foo"))) + .satisfies(ex -> { + assertEquals("Should have another started transaction", 2, ptm.begun); + assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); + }); } @Test 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 cbb468e6cb7..0e5778e1190 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,12 +38,11 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.config.TransactionManagementConfigUtils; import org.springframework.transaction.event.TransactionalEventListenerFactory; -import static org.hamcrest.CoreMatchers.containsString; +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; -import static org.junit.Assert.fail; /** * Tests demonstrating use of @EnableTransactionManagement @Configuration classes. @@ -118,14 +117,11 @@ public class EnableTransactionManagementTests { @Test @SuppressWarnings("resource") public void proxyTypeAspectJCausesRegistrationOfAnnotationTransactionAspect() { - try { - new AnnotationConfigApplicationContext(EnableAspectjTxConfig.class, TxManagerConfig.class); - fail("should have thrown CNFE when trying to load AnnotationTransactionAspect. " + - "Do you actually have org.springframework.aspects on the classpath?"); - } - catch (Exception ex) { - assertThat(ex.getMessage(), containsString("AspectJJtaTransactionManagementConfiguration")); - } + // should throw CNFE when trying to load AnnotationTransactionAspect. + // Do you actually have org.springframework.aspects on the classpath? + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + new AnnotationConfigApplicationContext(EnableAspectjTxConfig.class, TxManagerConfig.class)) + .withMessageContaining("AspectJJtaTransactionManagementConfiguration"); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java b/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java index c08ee812713..2accdb03fd1 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java @@ -46,9 +46,8 @@ import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.transaction.event.TransactionPhase.AFTER_COMMIT; import static org.springframework.transaction.event.TransactionPhase.AFTER_COMPLETION; import static org.springframework.transaction.event.TransactionPhase.AFTER_ROLLBACK; @@ -95,17 +94,14 @@ public class TransactionalEventListenerTests { @Test public void immediatelyImpactsCurrentTransaction() { load(ImmediateTestListener.class, BeforeCommitTestListener.class); - try { - this.transactionTemplate.execute(status -> { - getContext().publishEvent("FAIL"); - fail("Should have thrown an exception at this point"); - return null; - }); - } - catch (IllegalStateException e) { - assertTrue(e.getMessage().contains("Test exception")); - assertTrue(e.getMessage().contains(EventCollector.IMMEDIATELY)); - } + assertThatIllegalStateException().isThrownBy(() -> + this.transactionTemplate.execute(status -> { + getContext().publishEvent("FAIL"); + throw new AssertionError("Should have thrown an exception at this point"); + })) + .withMessageContaining("Test exception") + .withMessageContaining(EventCollector.IMMEDIATELY); + getEventCollector().assertEvents(EventCollector.IMMEDIATELY, "FAIL"); getEventCollector().assertTotalEventsCount(1); } @@ -203,24 +199,19 @@ public class TransactionalEventListenerTests { @Test public void beforeCommitWithException() { // Validates the custom synchronization is invoked load(BeforeCommitTestListener.class); - try { - this.transactionTemplate.execute(status -> { - TransactionSynchronizationManager.registerSynchronization(new EventTransactionSynchronization(10) { - @Override - public void beforeCommit(boolean readOnly) { - throw new IllegalStateException("test"); - } - }); - getContext().publishEvent("test"); - getEventCollector().assertNoEventReceived(); - return null; + assertThatIllegalStateException().isThrownBy(() -> + this.transactionTemplate.execute(status -> { + TransactionSynchronizationManager.registerSynchronization(new EventTransactionSynchronization(10) { + @Override + public void beforeCommit(boolean readOnly) { + throw new IllegalStateException("test"); + } + }); + getContext().publishEvent("test"); + getEventCollector().assertNoEventReceived(); + return null; - }); - fail("Should have thrown an exception"); - } - catch (IllegalStateException e) { - // Test exception - ignore - } + })); getEventCollector().assertNoEventReceived(); // Before commit not invoked } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java index d4f509f5cf3..34e961b303e 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java @@ -352,7 +352,7 @@ public abstract class AbstractReactiveTransactionAspectTests { private void checkReactiveTransaction(boolean expected) { Mono.subscriberContext().handle((context, sink) -> { - if (context.hasKey(TransactionContext.class) != expected){ + if (context.hasKey(TransactionContext.class) != expected) { fail("Should have thrown NoTransactionException"); } sink.complete(); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java index 7da7422d301..686b85b9001 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java @@ -34,6 +34,7 @@ import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.UnexpectedRollbackException; import org.springframework.transaction.interceptor.TransactionAspectSupport.TransactionInfo; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -157,13 +158,8 @@ public abstract class AbstractTransactionAspectTests { ITestBean itb = (ITestBean) advised(tb, ptm, tas); checkTransactionStatus(false); - try { - itb.exceptional(new OptimisticLockingFailureException("")); - fail("Should have thrown OptimisticLockingFailureException"); - } - catch (OptimisticLockingFailureException ex) { - // expected - } + assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> + itb.exceptional(new OptimisticLockingFailureException(""))); checkTransactionStatus(false); assertSame(txatt, ptm.getDefinition()); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java index 1ab4533bdfb..47b0c3b3155 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java @@ -42,11 +42,11 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; @@ -191,15 +191,11 @@ public class BeanFactoryTransactionTests { */ @Test public void testNoTransactionAttributeSource() { - try { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("noTransactionAttributeSource.xml", getClass())); - bf.getBean("noTransactionAttributeSource"); - fail("Should require TransactionAttributeSource to be set"); - } - catch (FatalBeanException ex) { - // Ok - } + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("noTransactionAttributeSource.xml", getClass())); + bf.getBean("noTransactionAttributeSource"); + }); } /** 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 423676c1a5d..9060b336c09 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,6 +22,7 @@ import org.junit.Test; import org.springframework.beans.FatalBeanException; +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; @@ -72,19 +73,22 @@ public class RollbackRuleTests { assertTrue(rr.getDepth(new RuntimeException()) > 0); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorArgMustBeAThrowableClassWithNonThrowableType() { - new RollbackRuleAttribute(StringBuffer.class); + assertThatIllegalArgumentException().isThrownBy(() -> + new RollbackRuleAttribute(StringBuffer.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorArgMustBeAThrowableClassWithNullThrowableType() { - new RollbackRuleAttribute((Class) null); + assertThatIllegalArgumentException().isThrownBy(() -> + new RollbackRuleAttribute((Class) null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void ctorArgExceptionStringNameVersionWithNull() { - new RollbackRuleAttribute((String) null); + assertThatIllegalArgumentException().isThrownBy(() -> + new RollbackRuleAttribute((String) null)); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java index 7a601dea0bf..0a2365d6c36 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.transaction.TransactionDefinition; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -66,11 +67,12 @@ public class TransactionAttributeEditorTests { assertTrue(!ta.isReadOnly()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInvalidPropagationCodeOnly() { TransactionAttributeEditor pe = new TransactionAttributeEditor(); // should have failed with bogus propagation code - pe.setAsText("XXPROPAGATION_REQUIRED"); + assertThatIllegalArgumentException().isThrownBy(() -> + pe.setAsText("XXPROPAGATION_REQUIRED")); } @Test @@ -83,11 +85,12 @@ public class TransactionAttributeEditorTests { assertTrue(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValidPropagationAndIsolationCodesAndInvalidRollbackRule() { TransactionAttributeEditor pe = new TransactionAttributeEditor(); // should fail with bogus rollback rule - pe.setAsText("PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,XXX"); + assertThatIllegalArgumentException().isThrownBy(() -> + pe.setAsText("PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,XXX")); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java index ea9ab3a631b..0a046363c14 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java @@ -22,6 +22,7 @@ import org.junit.Test; import org.springframework.transaction.TransactionDefinition; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -49,9 +50,10 @@ public class TransactionAttributeSourceEditorTests { assertNull(tas.getTransactionAttribute(m, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidFormat() throws Exception { - editor.setAsText("foo=bar"); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setAsText("foo=bar")); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java index a3cd98e712a..56b57197fbf 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java @@ -36,11 +36,11 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -109,18 +109,13 @@ public class WebSphereUowTransactionManagerTests { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY); - try { + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } - }); - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } + })); } @Test @@ -357,24 +352,21 @@ public class WebSphereUowTransactionManagerTests { assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - try { - ptm.execute(definition, new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - return "result"; - } + assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> + ptm.execute(definition, new TransactionCallback() { + @Override + public String doInTransaction(TransactionStatus status) { + assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + return "result"; + } + })) + .withCauseInstanceOf(UOWException.class) + .satisfies(ex -> { + assertThat(ex.getRootCause()).isSameAs(rex); + assertThat(ex.getMostSpecificCause()).isSameAs(rex); }); - fail("Should have thrown TransactionSystemException"); - } - catch (TransactionSystemException ex) { - // expected - assertTrue(ex.getCause() instanceof UOWException); - assertSame(rex, ex.getRootCause()); - assertSame(rex, ex.getMostSpecificCause()); - } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); @@ -393,7 +385,7 @@ public class WebSphereUowTransactionManagerTests { assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - try { + assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { @@ -402,12 +394,7 @@ public class WebSphereUowTransactionManagerTests { assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); throw new OptimisticLockingFailureException(""); } - }); - fail("Should have thrown OptimisticLockingFailureException"); - } - catch (OptimisticLockingFailureException ex) { - // expected - } + })); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); @@ -489,18 +476,13 @@ public class WebSphereUowTransactionManagerTests { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); - try { + assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } - }); - fail("Should have thrown IllegalTransactionStateException"); - } - catch (IllegalTransactionStateException ex) { - // expected - } + })); } @Test @@ -511,18 +493,13 @@ public class WebSphereUowTransactionManagerTests { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - try { + assertThatExceptionOfType(NestedTransactionNotSupportedException.class).isThrownBy(() -> ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } - }); - fail("Should have thrown NestedTransactionNotSupportedException"); - } - catch (NestedTransactionNotSupportedException ex) { - // expected - } + })); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java index 31ff7fc3e23..ef62396a6e0 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java @@ -28,11 +28,11 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.transaction.CallCountingTransactionManager; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -58,23 +58,13 @@ public class SimpleTransactionScopeTests { context.refresh(); - try { - context.getBean(TestBean.class); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - no synchronization active - assertTrue(ex.getCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + context.getBean(TestBean.class)) + .withCauseInstanceOf(IllegalStateException.class); - try { - context.getBean(DerivedTestBean.class); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - no synchronization active - assertTrue(ex.getCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + context.getBean(DerivedTestBean.class)) + .withCauseInstanceOf(IllegalStateException.class); TestBean bean1 = null; DerivedTestBean bean2 = null; @@ -113,23 +103,13 @@ public class SimpleTransactionScopeTests { assertTrue(bean2b.wasDestroyed()); assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - try { - context.getBean(TestBean.class); - fail("Should have thrown IllegalStateException"); - } - catch (BeanCreationException ex) { - // expected - no synchronization active - assertTrue(ex.getCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + context.getBean(TestBean.class)) + .withCauseInstanceOf(IllegalStateException.class); - try { - context.getBean(DerivedTestBean.class); - fail("Should have thrown IllegalStateException"); - } - catch (BeanCreationException ex) { - // expected - no synchronization active - assertTrue(ex.getCause() instanceof IllegalStateException); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + context.getBean(DerivedTestBean.class)) + .withCauseInstanceOf(IllegalStateException.class); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java b/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java index 66a64fe16b3..9acef2b8d4c 100644 --- a/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java +++ b/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java @@ -26,6 +26,7 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -80,19 +81,22 @@ public class ContentDispositionTests { .filename("中文.txt", StandardCharsets.UTF_8).build(), disposition); } - @Test(expected = IllegalArgumentException.class) + @Test public void parseEmpty() { - ContentDisposition.parse(""); + assertThatIllegalArgumentException().isThrownBy(() -> + ContentDisposition.parse("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void parseNoType() { - ContentDisposition.parse(";"); + assertThatIllegalArgumentException().isThrownBy(() -> + ContentDisposition.parse(";")); } - @Test(expected = IllegalArgumentException.class) + @Test public void parseInvalidParameter() { - ContentDisposition.parse("foo;bar"); + assertThatIllegalArgumentException().isThrownBy(() -> + ContentDisposition.parse("foo;bar")); } @Test @@ -147,12 +151,13 @@ public class ContentDispositionTests { assertEquals("UTF-8''%E4%B8%AD%E6%96%87.txt", result); } - @Test(expected = IllegalArgumentException.class) + @Test public void encodeHeaderFieldParamInvalidCharset() { Method encode = ReflectionUtils.findMethod(ContentDisposition.class, "encodeHeaderFieldParam", String.class, Charset.class); ReflectionUtils.makeAccessible(encode); - ReflectionUtils.invokeMethod(encode, null, "test", StandardCharsets.UTF_16); + assertThatIllegalArgumentException().isThrownBy(() -> + ReflectionUtils.invokeMethod(encode, null, "test", StandardCharsets.UTF_16)); } @Test // SPR-14408 @@ -168,12 +173,13 @@ public class ContentDispositionTests { assertEquals("中文.txt", result); } - @Test(expected = IllegalArgumentException.class) + @Test public void decodeHeaderFieldParamInvalidCharset() { Method decode = ReflectionUtils.findMethod(ContentDisposition.class, "decodeHeaderFieldParam", String.class); ReflectionUtils.makeAccessible(decode); - ReflectionUtils.invokeMethod(decode, null, "UTF-16''test"); + assertThatIllegalArgumentException().isThrownBy(() -> + ReflectionUtils.invokeMethod(decode, null, "UTF-16''test")); } } 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 75869b1affe..fa7f8848b14 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java @@ -37,6 +37,7 @@ import java.util.TimeZone; import org.hamcrest.Matchers; import org.junit.Test; +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.assertEquals; @@ -178,12 +179,11 @@ public class HttpHeadersTests { assertEquals("Invalid Host header", "[::1]", headers.getFirst("Host")); } - @Test(expected = IllegalArgumentException.class) + @Test public void illegalETag() { String eTag = "v2.6"; - headers.setETag(eTag); - assertEquals("Invalid ETag header", eTag, headers.getETag()); - assertEquals("Invalid ETag header", "\"v2.6\"", headers.getFirst("ETag")); + assertThatIllegalArgumentException().isThrownBy(() -> + headers.setETag(eTag)); } @Test @@ -194,10 +194,11 @@ public class HttpHeadersTests { assertEquals("Invalid If-Match header", "\"v2.6\"", headers.getFirst("If-Match")); } - @Test(expected = IllegalArgumentException.class) + @Test public void ifMatchIllegalHeader() { headers.setIfMatch("Illegal"); - headers.getIfMatch(); + assertThatIllegalArgumentException().isThrownBy( + headers::getIfMatch); } @Test @@ -251,10 +252,11 @@ public class HttpHeadersTests { assertEquals("Invalid Date header", date, headers.getDate()); } - @Test(expected = IllegalArgumentException.class) + @Test public void dateInvalid() { headers.set("Date", "Foo Bar Baz"); - headers.getDate(); + assertThatIllegalArgumentException().isThrownBy( + headers::getDate); } @Test @@ -549,11 +551,12 @@ public class HttpHeadersTests { assertEquals("foo:bar", new String(result, StandardCharsets.ISO_8859_1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void basicAuthIllegalChar() { String username = "foo"; String password = "\u03BB"; - headers.setBasicAuth(username, password); + assertThatIllegalArgumentException().isThrownBy(() -> + headers.setBasicAuth(username, password)); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java b/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java index 154d0646393..60ceacbd8e5 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java @@ -27,8 +27,8 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.support.ResourceRegion; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -40,19 +40,22 @@ import static org.mockito.Mockito.mock; */ public class HttpRangeTests { - @Test(expected = IllegalArgumentException.class) + @Test public void invalidFirstPosition() { - HttpRange.createByteRange(-1); + assertThatIllegalArgumentException().isThrownBy(() -> + HttpRange.createByteRange(-1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidLastLessThanFirst() { - HttpRange.createByteRange(10, 9); + assertThatIllegalArgumentException().isThrownBy(() -> + HttpRange.createByteRange(10, 9)); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidSuffixLength() { - HttpRange.createSuffixRange(-1); + assertThatIllegalArgumentException().isThrownBy(() -> + HttpRange.createSuffixRange(-1)); } @Test @@ -106,25 +109,20 @@ public class HttpRangeTests { public void parseRangesValidations() { // 1. At limit.. - StringBuilder sb = new StringBuilder("bytes=0-0"); + StringBuilder atLimit = new StringBuilder("bytes=0-0"); for (int i=0; i < 99; i++) { - sb.append(",").append(i).append("-").append(i + 1); + atLimit.append(",").append(i).append("-").append(i + 1); } - List ranges = HttpRange.parseRanges(sb.toString()); + List ranges = HttpRange.parseRanges(atLimit.toString()); assertEquals(100, ranges.size()); // 2. Above limit.. - sb = new StringBuilder("bytes=0-0"); + StringBuilder aboveLimit = new StringBuilder("bytes=0-0"); for (int i=0; i < 100; i++) { - sb.append(",").append(i).append("-").append(i + 1); - } - try { - HttpRange.parseRanges(sb.toString()); - fail(); - } - catch (IllegalArgumentException ex) { - // Expected + aboveLimit.append(",").append(i).append("-").append(i + 1); } + assertThatIllegalArgumentException().isThrownBy(() -> + HttpRange.parseRanges(aboveLimit.toString())); } @Test @@ -147,28 +145,31 @@ public class HttpRangeTests { assertEquals(6L, region.getCount()); } - @Test(expected = IllegalArgumentException.class) + @Test public void toResourceRegionInputStreamResource() { InputStreamResource resource = mock(InputStreamResource.class); HttpRange range = HttpRange.createByteRange(0, 9); - range.toResourceRegion(resource); + assertThatIllegalArgumentException().isThrownBy(() -> + range.toResourceRegion(resource)); } - @Test(expected = IllegalArgumentException.class) + @Test public void toResourceRegionIllegalLength() { ByteArrayResource resource = mock(ByteArrayResource.class); given(resource.contentLength()).willReturn(-1L); HttpRange range = HttpRange.createByteRange(0, 9); - range.toResourceRegion(resource); + assertThatIllegalArgumentException().isThrownBy(() -> + range.toResourceRegion(resource)); } - @Test(expected = IllegalArgumentException.class) + @Test @SuppressWarnings("unchecked") public void toResourceRegionExceptionLength() throws IOException { InputStreamResource resource = mock(InputStreamResource.class); given(resource.contentLength()).willThrow(IOException.class); HttpRange range = HttpRange.createByteRange(0, 9); - range.toResourceRegion(resource); + assertThatIllegalArgumentException().isThrownBy(() -> + range.toResourceRegion(resource)); } @Test @@ -177,19 +178,14 @@ public class HttpRangeTests { ByteArrayResource resource = new ByteArrayResource(bytes); // 1. Below length - List ranges = HttpRange.parseRanges("bytes=0-1,2-3"); - List regions = HttpRange.toResourceRegions(ranges, resource); + List belowLengthRanges = HttpRange.parseRanges("bytes=0-1,2-3"); + List regions = HttpRange.toResourceRegions(belowLengthRanges, resource); assertEquals(2, regions.size()); // 2. At length - ranges = HttpRange.parseRanges("bytes=0-1,2-4"); - try { - HttpRange.toResourceRegions(ranges, resource); - fail(); - } - catch (IllegalArgumentException ex) { - // Expected.. - } + List atLengthRanges = HttpRange.parseRanges("bytes=0-1,2-4"); + assertThatIllegalArgumentException().isThrownBy(() -> + HttpRange.toResourceRegions(atLengthRanges, resource)); } } diff --git a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java index 38c5ba5ae89..0fb56e18c5e 100644 --- a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java +++ b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java @@ -27,6 +27,8 @@ import org.junit.Test; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -46,14 +48,16 @@ public class MediaTypeTests { assertEquals("Invalid toString() returned", "text/plain;q=0.7", result); } - @Test(expected = IllegalArgumentException.class) + @Test public void slashInType() { - new MediaType("text/plain"); + assertThatIllegalArgumentException().isThrownBy(() -> + new MediaType("text/plain")); } - @Test(expected = IllegalArgumentException.class) + @Test public void slashInSubtype() { - new MediaType("text", "/"); + assertThatIllegalArgumentException().isThrownBy(() -> + new MediaType("text", "/")); } @Test @@ -71,59 +75,70 @@ public class MediaTypeTests { assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeNoSubtype() { - MediaType.parseMediaType("audio"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeNoSubtypeSlash() { - MediaType.parseMediaType("audio/"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeTypeRange() { - MediaType.parseMediaType("*/json"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("*/json")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeIllegalType() { - MediaType.parseMediaType("audio(/basic"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio(/basic")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeIllegalSubtype() { - MediaType.parseMediaType("audio/basic)"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/basic)")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeEmptyParameterAttribute() { - MediaType.parseMediaType("audio/*;=value"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/*;=value")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeEmptyParameterValue() { - MediaType.parseMediaType("audio/*;attr="); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/*;attr=")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeIllegalParameterAttribute() { - MediaType.parseMediaType("audio/*;attr<=value"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/*;attr<=value")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeIllegalParameterValue() { - MediaType.parseMediaType("audio/*;attr=v>alue"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/*;attr=v>alue")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeIllegalQualityFactor() { - MediaType.parseMediaType("audio/basic;q=1.1"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("audio/basic;q=1.1")); } - @Test(expected = InvalidMediaTypeException.class) + @Test public void parseMediaTypeIllegalCharset() { - MediaType.parseMediaType("text/html; charset=foo-bar"); + assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() -> + MediaType.parseMediaType("text/html; charset=foo-bar")); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java index bcaecd324e6..bd9e2a32d3d 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java @@ -36,9 +36,10 @@ import org.springframework.util.StreamUtils; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; @SuppressWarnings("deprecation") public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMockWebServerTestCase { @@ -94,12 +95,12 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo assertEquals("Invalid status code", HttpStatus.NOT_FOUND, result.getStatusCode()); } catch (IOException ex) { - fail(ex.getMessage()); + throw new AssertionError(ex.getMessage(), ex); } } @Override public void onFailure(Throwable ex) { - fail(ex.getMessage()); + throw new AssertionError(ex.getMessage(), ex); } }); ClientHttpResponse response = listenableFuture.get(); @@ -162,11 +163,8 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo Future futureResponse = request.executeAsync(); ClientHttpResponse response = futureResponse.get(); try { - FileCopyUtils.copy(body, request.getBody()); - fail("IllegalStateException expected"); - } - catch (IllegalStateException ex) { - // expected + assertThatIllegalStateException().isThrownBy(() -> + FileCopyUtils.copy(body, request.getBody())); } finally { response.close(); @@ -183,11 +181,8 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo Future futureResponse = request.executeAsync(); ClientHttpResponse response = futureResponse.get(); try { - request.getHeaders().add("MyHeader", "value"); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException ex) { - // expected + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + request.getHeaders().add("MyHeader", "value")); } finally { response.close(); diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java index 2b1b98fc482..86942c60375 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java @@ -32,6 +32,8 @@ import org.springframework.http.StreamingHttpOutputMessage; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -113,7 +115,7 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb } } - @Test(expected = IllegalStateException.class) + @Test public void multipleWrites() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); @@ -131,24 +133,22 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb } request.execute(); - FileCopyUtils.copy(body, request.getBody()); + assertThatIllegalStateException().isThrownBy(() -> + FileCopyUtils.copy(body, request.getBody())); } - @Test(expected = UnsupportedOperationException.class) + @Test public void headersAfterExecute() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST); request.getHeaders().add("MyHeader", "value"); byte[] body = "Hello World".getBytes("UTF-8"); - FileCopyUtils.copy(body, request.getBody()); - - ClientHttpResponse response = request.execute(); - try { - request.getHeaders().add("MyHeader", "value"); - } - finally { - response.close(); - } + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> { + FileCopyUtils.copy(body, request.getBody()); + try(ClientHttpResponse response = request.execute()) { + request.getHeaders().add("MyHeader", "value"); + } + }); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java index 8c7ea027548..679a9eb28ae 100644 --- a/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java @@ -22,6 +22,7 @@ import java.net.Proxy; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -36,22 +37,25 @@ public class ProxyFactoryBeanTests { factoryBean = new ProxyFactoryBean(); } - @Test(expected = IllegalArgumentException.class) + @Test public void noType() { factoryBean.setType(null); - factoryBean.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + factoryBean::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) + @Test public void noHostname() { factoryBean.setHostname(""); - factoryBean.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + factoryBean::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) + @Test public void noPort() { factoryBean.setHostname("example.com"); - factoryBean.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + factoryBean::afterPropertiesSet); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java index 04350796662..b66eb5550ed 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java @@ -31,6 +31,7 @@ import org.springframework.http.codec.Pojo; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.util.MimeType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.springframework.core.ResolvableType.forClass; @@ -66,16 +67,16 @@ public class Jackson2CborDecoderTests extends AbstractDecoderTestCase input = Flux.just(this.pojo1, this.pojo2) .map(this::writeObject) .flatMap(this::dataBuffer); - - testDecodeAll(input, Pojo.class, step -> step - .expectNext(pojo1) - .expectNext(pojo2) - .verifyComplete()); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + testDecodeAll(input, Pojo.class, step -> step + .expectNext(pojo1) + .expectNext(pojo2) + .verifyComplete())); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborEncoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborEncoderTests.java index 2f9d8190f16..b0b075372f0 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborEncoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborEncoderTests.java @@ -33,6 +33,7 @@ import org.springframework.http.codec.ServerSentEvent; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.util.MimeType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -92,13 +93,14 @@ public class Jackson2CborEncoderTests extends AbstractLeakCheckingTestCase { pojoConsumer(value).accept(result); } - @Test(expected = UnsupportedOperationException.class) + @Test public void encodeStream() { Pojo pojo1 = new Pojo("foo", "bar"); Pojo pojo2 = new Pojo("foofoo", "barbar"); Pojo pojo3 = new Pojo("foofoofoo", "barbarbar"); Flux input = Flux.just(pojo1, pojo2, pojo3); ResolvableType type = ResolvableType.forClass(Pojo.class); - encoder.encode(input, this.bufferFactory, type, CBOR_MIME_TYPE, null); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + encoder.encode(input, this.bufferFactory, type, CBOR_MIME_TYPE, null)); } } diff --git a/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java index e1885e5152d..23333490ca1 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java @@ -47,6 +47,7 @@ import org.springframework.util.MimeType; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -94,12 +95,13 @@ public class Jackson2JsonDecoderTests extends AbstractDecoderTestCase + decoder.getMimeTypes().add(new MimeType("text", "ecmascript"))); } @Override diff --git a/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java index ca2ec8a5133..ba7e9479953 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java @@ -44,6 +44,7 @@ import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -100,12 +101,13 @@ public class Jackson2JsonEncoderTests extends AbstractEncoderTestCase + encoder.getMimeTypes().add(new MimeType("text", "ecmascript"))); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultMultipartMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultMultipartMessageReaderTests.java index 80f5ab5937d..0986a3bcecb 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultMultipartMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultMultipartMessageReaderTests.java @@ -37,7 +37,6 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.core.ResolvableType.forClass; /** @@ -148,7 +147,9 @@ public class DefaultMultipartMessageReaderTests extends AbstractDataBufferAlloca CountDownLatch latch = new CountDownLatch(1); file.transferTo(tempFile) .subscribe(null, - throwable -> fail(throwable.getMessage()), + throwable -> { + throw new AssertionError(throwable.getMessage(), throwable); + }, () -> { try { verifyContents(tempFile, contents); diff --git a/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java index 9cfad69be5e..3cc50d037e7 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java @@ -36,6 +36,7 @@ import org.springframework.protobuf.SecondMsg; import org.springframework.util.MimeType; import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.springframework.core.ResolvableType.forClass; @@ -63,9 +64,10 @@ public class ProtobufDecoderTests extends AbstractDecoderTestCase + new ProtobufDecoder(null)); } @Override diff --git a/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java index 546b3337aa3..8d229cd45ce 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java @@ -26,7 +26,6 @@ import org.springframework.http.MediaType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test-case for AbstractHttpMessageConverter. @@ -92,14 +91,13 @@ public class HttpMessageConverterTests { @Override protected T readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { - fail("Not expected"); - return null; + throw new AssertionError("Not expected"); } @Override protected void writeInternal(T t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { - fail("Not expected"); + throw new AssertionError("Not expected"); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java index bb72f171f55..ed9d1ebd5e6 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java @@ -34,6 +34,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -171,9 +172,10 @@ public class ObjectToStringHttpMessageConverterTests { assertArrayEquals(new byte[] { -2, -1, 0, '9', 0, '5', 0, '8' }, this.servletResponse.getContentAsByteArray()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConversionServiceRequired() { - new ObjectToStringHttpMessageConverter(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ObjectToStringHttpMessageConverter(null)); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java index fb55d1bf4a3..926bff47305 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java @@ -35,6 +35,7 @@ import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -166,12 +167,13 @@ public class GsonHttpMessageConverterTests { assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType()); } - @Test(expected = HttpMessageNotReadableException.class) + @Test public void readInvalidJson() throws IOException { String body = "FooBar"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); - this.converter.read(MyBean.class, inputMessage); + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + this.converter.read(MyBean.class, inputMessage)); } @Test 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 843d59e0cc1..05988bc4742 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,6 +83,8 @@ import org.junit.Test; import org.springframework.beans.FatalBeanException; import org.springframework.util.StringUtils; +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; @@ -107,9 +109,10 @@ public class Jackson2ObjectMapperBuilderTests { private static final String DATA = "{\"offsetDateTime\": \"2020-01-01T00:00:00\"}"; - @Test(expected = FatalBeanException.class) + @Test public void unknownFeature() { - Jackson2ObjectMapperBuilder.json().featuresToEnable(Boolean.TRUE).build(); + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + Jackson2ObjectMapperBuilder.json().featuresToEnable(Boolean.TRUE).build()); } @Test @@ -226,10 +229,11 @@ public class Jackson2ObjectMapperBuilderTests { assertEquals(timeZone, objectMapper.getDeserializationConfig().getTimeZone()); } - @Test(expected = IllegalArgumentException.class) + @Test public void wrongTimeZoneStringSetter() { String zoneId = "foo"; - Jackson2ObjectMapperBuilder.json().timeZone(zoneId).build(); + assertThatIllegalArgumentException().isThrownBy(() -> + Jackson2ObjectMapperBuilder.json().timeZone(zoneId).build()); } @Test 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 b5400b7e5e3..7f7ca552b54 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,6 +64,7 @@ import org.junit.Test; import org.springframework.beans.FatalBeanException; +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; @@ -91,10 +92,11 @@ public class Jackson2ObjectMapperFactoryBeanTests { private final Jackson2ObjectMapperFactoryBean factory = new Jackson2ObjectMapperFactoryBean(); - @Test(expected = FatalBeanException.class) + @Test public void unknownFeature() { this.factory.setFeaturesToEnable(Boolean.TRUE); - this.factory.afterPropertiesSet(); + assertThatExceptionOfType(FatalBeanException.class).isThrownBy( + this.factory::afterPropertiesSet); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java index 1cb902015ec..380f756f951 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java @@ -35,6 +35,7 @@ import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -166,12 +167,13 @@ public class JsonbHttpMessageConverterTests { assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType()); } - @Test(expected = HttpMessageNotReadableException.class) + @Test public void readInvalidJson() throws IOException { String body = "FooBar"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); - this.converter.read(MyBean.class, inputMessage); + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + this.converter.read(MyBean.class, inputMessage)); } @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 e34b0736252..8427f2739c4 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,13 +42,13 @@ import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.lang.Nullable; +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; -import static org.junit.Assert.fail; /** * Jackson 2.x converter tests. @@ -180,12 +180,13 @@ public class MappingJackson2HttpMessageConverterTests { assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType()); } - @Test(expected = HttpMessageNotReadableException.class) + @Test public void readInvalidJson() throws IOException { String body = "FooBar"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); - converter.read(MyBean.class, inputMessage); + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + converter.read(MyBean.class, inputMessage)); } @Test @@ -442,14 +443,9 @@ public class MappingJackson2HttpMessageConverterTests { String body = "{\"property1\":\"foo\",\"property2\":\"bar\"}"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); - try { - converter.read(BeanWithNoDefaultConstructor.class, inputMessage); - } - catch (HttpMessageConversionException ex) { - assertTrue(ex.getMessage(), ex.getMessage().startsWith("Type definition error:")); - return; - } - fail(); + assertThatExceptionOfType(HttpMessageConversionException.class).isThrownBy(() -> + converter.read(BeanWithNoDefaultConstructor.class, inputMessage)) + .withMessageStartingWith("Type definition error:"); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java index 83d3a08e867..f1709542784 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java @@ -32,10 +32,10 @@ import org.springframework.oxm.MarshallingFailureException; import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.UnmarshallingFailureException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -104,13 +104,9 @@ public class MarshallingHttpMessageConverterTests { given(unmarshaller.unmarshal(isA(StreamSource.class))).willReturn(Integer.valueOf(3)); MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller); - try { - converter.read(String.class, inputMessage); - fail("Should have thrown HttpMessageNotReadableException"); - } - catch (HttpMessageNotReadableException ex) { - assertTrue(ex.getCause() instanceof TypeMismatchException); - } + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + converter.read(String.class, inputMessage)) + .withCauseInstanceOf(TypeMismatchException.class); } @Test @@ -124,13 +120,9 @@ public class MarshallingHttpMessageConverterTests { MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(); converter.setUnmarshaller(unmarshaller); - try { - converter.read(Object.class, inputMessage); - fail("HttpMessageNotReadableException should be thrown"); - } - catch (HttpMessageNotReadableException e) { - assertTrue("Invalid exception hierarchy", e.getCause() == ex); - } + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + converter.read(Object.class, inputMessage)) + .withCause(ex); } @Test @@ -157,18 +149,15 @@ public class MarshallingHttpMessageConverterTests { Marshaller marshaller = mock(Marshaller.class); willThrow(ex).given(marshaller).marshal(eq(body), isA(Result.class)); - try { - MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); - converter.write(body, null, outputMessage); - fail("HttpMessageNotWritableException should be thrown"); - } - catch (HttpMessageNotWritableException e) { - assertTrue("Invalid exception hierarchy", e.getCause() == ex); - } + MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); + assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> + converter.write(body, null, outputMessage)) + .withCause(ex); } - @Test(expected = UnsupportedOperationException.class) + @Test public void supports() throws Exception { - new MarshallingHttpMessageConverter().supports(Object.class); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + new MarshallingHttpMessageConverter().supports(Object.class)); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java index 5dd5c04f4ad..71b26babaef 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java @@ -30,10 +30,10 @@ import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link ContextPathCompositeHandler}. @@ -50,13 +50,9 @@ public class ContextPathCompositeHandlerTests { } private void testInvalid(String contextPath, String expectedError) { - try { - new ContextPathCompositeHandler(Collections.singletonMap(contextPath, new TestHttpHandler())); - fail(); - } - catch (IllegalArgumentException ex) { - assertEquals(expectedError, ex.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + new ContextPathCompositeHandler(Collections.singletonMap(contextPath, new TestHttpHandler()))) + .withMessage(expectedError); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java index 0b861795a33..ffbbd7aabe0 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java @@ -34,6 +34,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; @@ -110,9 +111,10 @@ public class ServerHttpRequestTests { assertEquals("/app", request.getPath().contextPath().value()); } - @Test(expected = IllegalArgumentException.class) + @Test public void mutateWithInvalidPath() throws Exception { - createHttpRequest("/").mutate().path("foo-bar"); + assertThatIllegalArgumentException().isThrownBy(() -> + createHttpRequest("/").mutate().path("foo-bar")); } @Test // SPR-16434 diff --git a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java index 6ab61f1db77..2d99c5e6ba9 100644 --- a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java @@ -46,11 +46,12 @@ import org.springframework.remoting.support.RemoteInvocationResult; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -118,20 +119,10 @@ public class HttpInvokerTests { assertTrue(Arrays.equals(new int[] {1, 2, 3}, intArray[0])); assertTrue(Arrays.equals(new int[] {4, 5, 6}, intArray[1])); - try { - proxy.exceptional(new IllegalStateException()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - try { - proxy.exceptional(new IllegalAccessException()); - fail("Should have thrown IllegalAccessException"); - } - catch (IllegalAccessException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + proxy.exceptional(new IllegalStateException())); + assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() -> + proxy.exceptional(new IllegalAccessException())); } @Test @@ -157,14 +148,9 @@ public class HttpInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - try { - proxy.setAge(50); - fail("Should have thrown RemoteAccessException"); - } - catch (RemoteAccessException ex) { - // expected - assertTrue(ex.getCause() instanceof IOException); - } + assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> + proxy.setAge(50)) + .withCauseInstanceOf(IOException.class); } @Test @@ -236,20 +222,10 @@ public class HttpInvokerTests { proxy.setAge(50); assertEquals(50, proxy.getAge()); - try { - proxy.exceptional(new IllegalStateException()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - try { - proxy.exceptional(new IllegalAccessException()); - fail("Should have thrown IllegalAccessException"); - } - catch (IllegalAccessException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + proxy.exceptional(new IllegalStateException())); + assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() -> + proxy.exceptional(new IllegalAccessException())); } @Test @@ -316,20 +292,10 @@ public class HttpInvokerTests { proxy.setAge(50); assertEquals(50, proxy.getAge()); - try { - proxy.exceptional(new IllegalStateException()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - try { - proxy.exceptional(new IllegalAccessException()); - fail("Should have thrown IllegalAccessException"); - } - catch (IllegalAccessException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + proxy.exceptional(new IllegalStateException())); + assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() -> + proxy.exceptional(new IllegalAccessException())); } @Test @@ -360,13 +326,8 @@ public class HttpInvokerTests { public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) { RemoteInvocation invocation = new RemoteInvocation(methodInvocation); invocation.addAttribute("myKey", "myValue"); - try { - invocation.addAttribute("myKey", "myValue"); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected: already defined - } + assertThatIllegalStateException().isThrownBy(() -> + invocation.addAttribute("myKey", "myValue")); assertNotNull(invocation.getAttributes()); assertEquals(1, invocation.getAttributes().size()); assertEquals("myValue", invocation.getAttributes().get("myKey")); @@ -472,14 +433,10 @@ public class HttpInvokerTests { assertTrue(proxy.equals(proxy)); // should go through - try { - proxy.setAge(50); - fail("Should have thrown RemoteAccessException"); - } - catch (RemoteAccessException ex) { - // expected - assertTrue(ex.getCause() instanceof IOException); - } + + assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> + proxy.setAge(50)) + .withCauseInstanceOf(IOException.class); } diff --git a/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java index 070660e8983..d3a61cd8ade 100644 --- a/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java @@ -36,9 +36,9 @@ import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; import org.springframework.remoting.RemoteAccessException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -101,30 +101,20 @@ public class JaxWsSupportTests { String order = orderService.getOrder(1000); assertEquals("order 1000", order); - try { - orderService.getOrder(0); - fail("Should have thrown OrderNotFoundException"); - } - catch (OrderNotFoundException ex) { - // expected - } - catch (RemoteAccessException ex) { - // ignore - probably setup issue with JAX-WS provider vs JAXB - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + orderService.getOrder(0)) + .matches(ex -> ex instanceof OrderNotFoundException || + ex instanceof RemoteAccessException); + // ignore RemoteAccessException as probably setup issue with JAX-WS provider vs JAXB ServiceAccessor serviceAccessor = ac.getBean("accessor", ServiceAccessor.class); order = serviceAccessor.orderService.getOrder(1000); assertEquals("order 1000", order); - try { - serviceAccessor.orderService.getOrder(0); - fail("Should have thrown OrderNotFoundException"); - } - catch (OrderNotFoundException ex) { - // expected - } - catch (WebServiceException ex) { - // ignore - probably setup issue with JAX-WS provider vs JAXB - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + serviceAccessor.orderService.getOrder(0)) + .matches(ex -> ex instanceof OrderNotFoundException || + ex instanceof WebServiceException); + // ignore WebServiceException as probably setup issue with JAX-WS provider vs JAXB } catch (BeanCreationException ex) { if ("exporter".equals(ex.getBeanName()) && ex.getRootCause() instanceof ClassNotFoundException) { diff --git a/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java index ab6c38ffecd..d59bfdc3ccd 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java @@ -33,6 +33,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -128,7 +129,7 @@ public class ContentNegotiationManagerFactoryBeanTests { assertEquals(Collections.singletonList(MediaType.IMAGE_GIF), manager.resolveMediaTypes(this.webRequest)); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170 + @Test // SPR-10170 public void favorPathWithIgnoreUnknownPathExtensionTurnedOff() throws Exception { this.factoryBean.setFavorPathExtension(true); this.factoryBean.setIgnoreUnknownPathExtensions(false); @@ -138,7 +139,8 @@ public class ContentNegotiationManagerFactoryBeanTests { this.servletRequest.setRequestURI("/flower.foobarbaz"); this.servletRequest.addParameter("format", "json"); - manager.resolveMediaTypes(this.webRequest); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + manager.resolveMediaTypes(this.webRequest)); } @Test @@ -159,7 +161,7 @@ public class ContentNegotiationManagerFactoryBeanTests { manager.resolveMediaTypes(this.webRequest)); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170 + @Test // SPR-10170 public void favorParameterWithUnknownMediaType() throws HttpMediaTypeNotAcceptableException { this.factoryBean.setFavorParameter(true); this.factoryBean.afterPropertiesSet(); @@ -168,7 +170,8 @@ public class ContentNegotiationManagerFactoryBeanTests { this.servletRequest.setRequestURI("/flower"); this.servletRequest.setParameter("format", "invalid"); - manager.resolveMediaTypes(this.webRequest); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + manager.resolveMediaTypes(this.webRequest)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java b/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java index dd234ec29e2..3c70a9279a5 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java @@ -26,6 +26,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -68,10 +69,11 @@ public class HeaderContentNegotiationStrategyTests { assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString()); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) + @Test public void resolveMediaTypesParseError() throws Exception { this.servletRequest.addHeader("Accept", "textplain; q=0.5"); - this.strategy.resolveMediaTypes(this.webRequest); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + this.strategy.resolveMediaTypes(this.webRequest)); } } diff --git a/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java b/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java index a7c8fe1711d..ce1623d23a6 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java @@ -29,6 +29,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -122,14 +123,15 @@ public class PathExtensionContentNegotiationStrategyTests { assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) + @Test public void resolveMediaTypesDoNotIgnoreUnknownExtension() throws Exception { this.servletRequest.setRequestURI("test.foobar"); PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(); strategy.setIgnoreUnknownExtensions(false); - strategy.resolveMediaTypes(this.webRequest); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + strategy.resolveMediaTypes(this.webRequest)); } } diff --git a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java index 15410024936..89a7059a9ac 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java @@ -23,11 +23,11 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.util.StopWatch; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -48,31 +48,16 @@ public class ServletRequestUtilsTests { assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5); assertEquals(ServletRequestUtils.getIntParameter(request, "param2", 6), 6); - try { - ServletRequestUtils.getRequiredIntParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredIntParameter(request, "param2")); assertEquals(ServletRequestUtils.getIntParameter(request, "param3"), null); assertEquals(ServletRequestUtils.getIntParameter(request, "param3", 6), 6); - try { - ServletRequestUtils.getRequiredIntParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredIntParameter(request, "param3")); - try { - ServletRequestUtils.getRequiredIntParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredIntParameter(request, "paramEmpty")); } @Test @@ -91,13 +76,8 @@ public class ServletRequestUtilsTests { assertEquals(array[i], values[i]); } - try { - ServletRequestUtils.getRequiredIntParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredIntParameters(request, "param2")); } @Test @@ -112,31 +92,16 @@ public class ServletRequestUtilsTests { assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5L); assertEquals(ServletRequestUtils.getLongParameter(request, "param2", 6L), 6L); - try { - ServletRequestUtils.getRequiredLongParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredLongParameter(request, "param2")); assertEquals(ServletRequestUtils.getLongParameter(request, "param3"), null); assertEquals(ServletRequestUtils.getLongParameter(request, "param3", 6L), 6L); - try { - ServletRequestUtils.getRequiredLongParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredLongParameter(request, "param3")); - try { - ServletRequestUtils.getRequiredLongParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredLongParameter(request, "paramEmpty")); } @Test @@ -156,13 +121,8 @@ public class ServletRequestUtilsTests { assertEquals(array[i], values[i]); } - try { - ServletRequestUtils.getRequiredLongParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredLongParameters(request, "param2")); request.setParameter("param2", new String[] {"1", "2"}); values = ServletRequestUtils.getRequiredLongParameters(request, "param2"); @@ -171,13 +131,8 @@ public class ServletRequestUtilsTests { assertEquals(2, values[1]); request.removeParameter("param2"); - try { - ServletRequestUtils.getRequiredLongParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredLongParameters(request, "param2")); } @Test @@ -192,31 +147,16 @@ public class ServletRequestUtilsTests { assertTrue(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f); assertTrue(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f); - try { - ServletRequestUtils.getRequiredFloatParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredFloatParameter(request, "param2")); assertTrue(ServletRequestUtils.getFloatParameter(request, "param3") == null); assertTrue(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f); - try { - ServletRequestUtils.getRequiredFloatParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredFloatParameter(request, "param3")); - try { - ServletRequestUtils.getRequiredFloatParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredFloatParameter(request, "paramEmpty")); } @Test @@ -235,13 +175,8 @@ public class ServletRequestUtilsTests { assertEquals(array[i], values[i], 0); } - try { - ServletRequestUtils.getRequiredFloatParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredFloatParameters(request, "param2")); } @Test @@ -256,31 +191,16 @@ public class ServletRequestUtilsTests { assertTrue(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5); assertTrue(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5); - try { - ServletRequestUtils.getRequiredDoubleParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredDoubleParameter(request, "param2")); assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3") == null); assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5); - try { - ServletRequestUtils.getRequiredDoubleParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredDoubleParameter(request, "param3")); - try { - ServletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty")); } @Test @@ -299,13 +219,8 @@ public class ServletRequestUtilsTests { assertEquals(array[i], values[i], 0); } - try { - ServletRequestUtils.getRequiredDoubleParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredDoubleParameters(request, "param2")); } @Test @@ -326,13 +241,8 @@ public class ServletRequestUtilsTests { assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3") == null); assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3", true)); - try { - ServletRequestUtils.getRequiredBooleanParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredBooleanParameter(request, "param3")); assertTrue(ServletRequestUtils.getBooleanParameter(request, "param4", false)); assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param4")); @@ -379,13 +289,8 @@ public class ServletRequestUtilsTests { assertEquals(null, ServletRequestUtils.getStringParameter(request, "param3")); assertEquals("string", ServletRequestUtils.getStringParameter(request, "param3", "string")); assertNull(ServletRequestUtils.getStringParameter(request, "param3", null)); - try { - ServletRequestUtils.getRequiredStringParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + ServletRequestUtils.getRequiredStringParameter(request, "param3")); assertEquals("", ServletRequestUtils.getStringParameter(request, "paramEmpty")); assertEquals("", ServletRequestUtils.getRequiredStringParameter(request, "paramEmpty")); diff --git a/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java index 993b2ec32cb..fa548af6d2a 100644 --- a/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java @@ -44,6 +44,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -351,19 +352,17 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest @Test public void notFoundGet() throws Exception { - try { - Future future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); - future.get(); - fail("HttpClientErrorException expected"); - } - catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof HttpClientErrorException); - HttpClientErrorException cause = (HttpClientErrorException)ex.getCause(); - - assertEquals(HttpStatus.NOT_FOUND, cause.getStatusCode()); - assertNotNull(cause.getStatusText()); - assertNotNull(cause.getResponseBodyAsString()); - } + assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> { + Future future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); + future.get(); + }) + .withCauseInstanceOf(HttpClientErrorException.class) + .satisfies(ex -> { + HttpClientErrorException cause = (HttpClientErrorException) ex.getCause(); + assertEquals(HttpStatus.NOT_FOUND, cause.getStatusCode()); + assertNotNull(cause.getStatusText()); + assertNotNull(cause.getResponseBodyAsString()); + }); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java index 9254a59bc9f..ace47e6bea2 100644 --- a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java @@ -26,9 +26,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.http.HttpStatus.BAD_GATEWAY; @@ -104,14 +103,8 @@ public class DefaultResponseErrorHandlerHttpStatusTests { given(this.response.getRawStatusCode()).willReturn(this.httpStatus.value()); given(this.response.getHeaders()).willReturn(headers); - try { - this.handler.handleError(this.response); - fail("expected " + this.expectedExceptionClass.getSimpleName()); - } - catch (HttpStatusCodeException ex) { - assertEquals("Expected " + this.expectedExceptionClass.getSimpleName(), - this.expectedExceptionClass, ex.getClass()); - } + assertThatExceptionOfType(expectedExceptionClass).isThrownBy(() -> + this.handler.handleError(this.response)); } } diff --git a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java index b3b52bfcce9..d4952e53fc4 100644 --- a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java @@ -28,11 +28,11 @@ import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -72,16 +72,12 @@ public class DefaultResponseErrorHandlerTests { given(response.getHeaders()).willReturn(headers); given(response.getBody()).willReturn(new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8))); - try { - handler.handleError(response); - fail("expected HttpClientErrorException"); - } - catch (HttpClientErrorException ex) { - assertSame(headers, ex.getResponseHeaders()); - } + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + handler.handleError(response)) + .satisfies(ex -> assertThat(ex.getResponseHeaders()).isSameAs(headers)); } - @Test(expected = HttpClientErrorException.class) + @Test public void handleErrorIOException() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); @@ -91,10 +87,11 @@ public class DefaultResponseErrorHandlerTests { given(response.getHeaders()).willReturn(headers); given(response.getBody()).willThrow(new IOException()); - handler.handleError(response); + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + handler.handleError(response)); } - @Test(expected = HttpClientErrorException.class) + @Test public void handleErrorNullResponse() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); @@ -103,7 +100,8 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Not Found"); given(response.getHeaders()).willReturn(headers); - handler.handleError(response); + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + handler.handleError(response)); } @Test // SPR-16108 @@ -118,7 +116,7 @@ public class DefaultResponseErrorHandlerTests { assertFalse(handler.hasError(response)); } - @Test(expected = UnknownHttpStatusCodeException.class) // SPR-9406 + @Test // SPR-9406 public void handleErrorUnknownStatusCode() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); @@ -127,7 +125,8 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); - handler.handleError(response); + assertThatExceptionOfType(UnknownHttpStatusCodeException.class).isThrownBy(() -> + handler.handleError(response)); } @Test // SPR-17461 @@ -142,7 +141,7 @@ public class DefaultResponseErrorHandlerTests { assertTrue(handler.hasError(response)); } - @Test(expected = UnknownHttpStatusCodeException.class) + @Test public void handleErrorForCustomClientError() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); @@ -151,7 +150,8 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); - handler.handleError(response); + assertThatExceptionOfType(UnknownHttpStatusCodeException.class).isThrownBy(() -> + handler.handleError(response)); } @Test // SPR-17461 @@ -166,7 +166,7 @@ public class DefaultResponseErrorHandlerTests { assertTrue(handler.hasError(response)); } - @Test(expected = UnknownHttpStatusCodeException.class) + @Test public void handleErrorForCustomServerError() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); @@ -175,7 +175,8 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); - handler.handleError(response); + assertThatExceptionOfType(UnknownHttpStatusCodeException.class).isThrownBy(() -> + handler.handleError(response)); } @Test // SPR-16604 diff --git a/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java b/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java index ba5bdd2a90d..8ebcbe0a2f5 100644 --- a/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java @@ -30,11 +30,12 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -99,13 +100,9 @@ public class ExtractingResponseErrorHandlerTests { responseHeaders.setContentLength(body.length); given(this.response.getBody()).willReturn(new ByteArrayInputStream(body)); - try { - this.errorHandler.handleError(this.response); - fail("MyRestClientException expected"); - } - catch (MyRestClientException ex) { - assertEquals("bar", ex.getFoo()); - } + assertThatExceptionOfType(MyRestClientException.class).isThrownBy(() -> + this.errorHandler.handleError(this.response)) + .satisfies(ex -> assertThat(ex.getFoo()).isEqualTo("bar")); } @Test @@ -119,13 +116,9 @@ public class ExtractingResponseErrorHandlerTests { responseHeaders.setContentLength(body.length); given(this.response.getBody()).willReturn(new ByteArrayInputStream(body)); - try { - this.errorHandler.handleError(this.response); - fail("MyRestClientException expected"); - } - catch (MyRestClientException ex) { - assertEquals("bar", ex.getFoo()); - } + assertThatExceptionOfType(MyRestClientException.class).isThrownBy(() -> + this.errorHandler.handleError(this.response)) + .satisfies(ex -> assertThat(ex.getFoo()).isEqualTo("bar")); } @Test @@ -139,14 +132,12 @@ public class ExtractingResponseErrorHandlerTests { responseHeaders.setContentLength(body.length); given(this.response.getBody()).willReturn(new ByteArrayInputStream(body)); - try { - this.errorHandler.handleError(this.response); - fail("HttpClientErrorException expected"); - } - catch (HttpClientErrorException ex) { - assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); - assertArrayEquals(body, ex.getResponseBodyAsByteArray()); - } + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + this.errorHandler.handleError(this.response)) + .satisfies(ex -> { + assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); + assertArrayEquals(body, ex.getResponseBodyAsByteArray()); + }); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java index 1fec08b9c12..af5e3dbc02a 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java @@ -54,13 +54,13 @@ import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.springframework.http.HttpMethod.POST; @@ -173,40 +173,34 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase @Test public void notFound() { - try { - template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); - fail("HttpClientErrorException expected"); - } - catch (HttpClientErrorException ex) { - assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); - assertNotNull(ex.getStatusText()); - assertNotNull(ex.getResponseBodyAsString()); - } + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null)) + .satisfies(ex -> { + assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); + assertNotNull(ex.getStatusText()); + assertNotNull(ex.getResponseBodyAsString()); + }); } @Test public void badRequest() { - try { - template.execute(baseUrl + "/status/badrequest", HttpMethod.GET, null, null); - fail("HttpClientErrorException.BadRequest expected"); - } - catch (HttpClientErrorException.BadRequest ex) { - assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode()); - assertEquals("400 Client Error", ex.getMessage()); - } + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + template.execute(baseUrl + "/status/badrequest", HttpMethod.GET, null, null)) + .satisfies(ex -> { + assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode()); + assertEquals("400 Client Error", ex.getMessage()); + }); } @Test public void serverError() { - try { - template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null); - fail("HttpServerErrorException expected"); - } - catch (HttpServerErrorException ex) { - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode()); - assertNotNull(ex.getStatusText()); - assertNotNull(ex.getResponseBodyAsString()); - } + assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> + template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null)) + .satisfies(ex -> { + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode()); + assertNotNull(ex.getStatusText()); + assertNotNull(ex.getResponseBodyAsString()); + }); } @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 031762039f3..daf79db0009 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,13 +47,13 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.StreamUtils; import org.springframework.web.util.DefaultUriBuilderFactory; +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; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -168,13 +168,8 @@ public class RestTemplateTests { willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)) .given(errorHandler).handleError(new URI(url), GET, response); - try { - template.execute(url, GET, null, null); - fail("HttpServerErrorException expected"); - } - catch (HttpServerErrorException ex) { - // expected - } + assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> + template.execute(url, GET, null, null)); verify(response).close(); } @@ -209,13 +204,8 @@ public class RestTemplateTests { mockResponseBody("Foo", new MediaType("bar", "baz")); given(converter.canRead(String.class, barBaz)).willReturn(false); - try { - template.getForObject("https://example.com/{p}", String.class, "resource"); - fail("UnsupportedMediaTypeException expected"); - } - catch (RestClientException ex) { - // expected - } + assertThatExceptionOfType(RestClientException.class).isThrownBy(() -> + template.getForObject("https://example.com/{p}", String.class, "resource")); verify(response).close(); } @@ -547,15 +537,10 @@ public class RestTemplateTests { mockHttpMessageConverter(new MediaType("foo", "bar"), String.class); given(request.execute()).willThrow(new IOException("Socket failure")); - try { - template.getForObject(url, String.class); - fail("RestClientException expected"); - } - catch (ResourceAccessException ex) { - assertEquals("I/O error on GET request for \"https://example.com/resource\": " + - "Socket failure; nested exception is java.io.IOException: Socket failure", - ex.getMessage()); - } + assertThatExceptionOfType(ResourceAccessException.class).isThrownBy(() -> + template.getForObject(url, String.class)) + .withMessage("I/O error on GET request for \"https://example.com/resource\": " + + "Socket failure; nested exception is java.io.IOException: Socket failure"); } @Test // SPR-15900 @@ -570,15 +555,10 @@ public class RestTemplateTests { given(request.getHeaders()).willReturn(new HttpHeaders()); given(request.execute()).willThrow(new IOException("Socket failure")); - try { - template.getForObject(uri, String.class); - fail("RestClientException expected"); - } - catch (ResourceAccessException ex) { - assertEquals("I/O error on GET request for \"https://example.com/resource\": " + - "Socket failure; nested exception is java.io.IOException: Socket failure", - ex.getMessage()); - } + assertThatExceptionOfType(ResourceAccessException.class).isThrownBy(() -> + template.getForObject(uri, String.class)) + .withMessage("I/O error on GET request for \"https://example.com/resource\": " + + "Socket failure; nested exception is java.io.IOException: Socket failure"); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java index b7e187c06f5..6f1436af81d 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java @@ -27,10 +27,10 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -69,13 +69,8 @@ public class RequestAndSessionScopedBeanTests { assertNotSame(target3, target); RequestContextHolder.setRequestAttributes(null); - try { - wac.getBean(targetBeanName); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + wac.getBean(targetBeanName)); } @Test @@ -97,15 +92,8 @@ public class RequestAndSessionScopedBeanTests { assertSame(target, request.getSession().getAttribute(targetBeanName)); RequestContextHolder.setRequestAttributes(null); - try { - wac.getBean(targetBeanName); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - } - - + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + wac.getBean(targetBeanName)); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java index a053b952bc1..923d823e3c3 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java @@ -31,6 +31,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -38,7 +39,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -117,16 +117,11 @@ public class RequestScopeTests { RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "requestScopedObjectCircle1"; - assertNull(request.getAttribute(name)); - - this.beanFactory.getBean(name); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - assertTrue(ex.contains(BeanCurrentlyInCreationException.class)); - } + String name = "requestScopedObjectCircle1"; + assertNull(request.getAttribute(name)); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + this.beanFactory.getBean(name)) + .matches(ex -> ex.contains(BeanCurrentlyInCreationException.class)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java index 6a5ee380f23..dbd4a1417a3 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java @@ -26,9 +26,10 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpSession; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -49,9 +50,10 @@ public class ServletRequestAttributesTests { }; - @Test(expected = IllegalArgumentException.class) + @Test public void ctorRejectsNullArg() throws Exception { - new ServletRequestAttributes(null); + assertThatIllegalArgumentException().isThrownBy(() -> + new ServletRequestAttributes(null)); } @Test @@ -68,13 +70,8 @@ public class ServletRequestAttributesTests { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestAttributes attrs = new ServletRequestAttributes(request); request.close(); - try { - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java index f1e3fa445a9..9defe742bf2 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java @@ -26,14 +26,12 @@ import org.springframework.mock.web.test.MockAsyncContext; 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.containsString; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -93,25 +91,17 @@ public class StandardServletAsyncWebRequestTests { @Test public void startAsyncNotSupported() throws Exception { this.request.setAsyncSupported(false); - try { - this.asyncRequest.startAsync(); - fail("expected exception"); - } - catch (IllegalStateException ex) { - assertThat(ex.getMessage(), containsString("Async support must be enabled")); - } + assertThatIllegalStateException().isThrownBy( + this.asyncRequest::startAsync) + .withMessageContaining("Async support must be enabled"); } @Test public void startAsyncAfterCompleted() throws Exception { this.asyncRequest.onComplete(new AsyncEvent(new MockAsyncContext(this.request, this.response))); - try { - this.asyncRequest.startAsync(); - fail("expected exception"); - } - catch (IllegalStateException ex) { - assertEquals("Async processing has already completed", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy( + this.asyncRequest::startAsync) + .withMessage("Async processing has already completed"); } @Test @@ -138,10 +128,11 @@ public class StandardServletAsyncWebRequestTests { verify(errorHandler).accept(e); } - @Test(expected = IllegalStateException.class) + @Test public void setTimeoutDuringConcurrentHandling() { this.asyncRequest.startAsync(); - this.asyncRequest.setTimeout(25L); + assertThatIllegalStateException().isThrownBy(() -> + this.asyncRequest.setTimeout(25L)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java index 2a79d7424bc..ef8a14b5169 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java @@ -27,10 +27,12 @@ import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.test.MockHttpServletRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.BDDMockito.given; @@ -69,21 +71,13 @@ public class WebAsyncManagerTests { public void startAsyncProcessingWithoutAsyncWebRequest() throws Exception { WebAsyncManager manager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest()); - try { - manager.startCallableProcessing(new StubCallable(1)); - fail("Expected exception"); - } - catch (IllegalStateException ex) { - assertEquals("AsyncWebRequest must not be null", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + manager.startCallableProcessing(new StubCallable(1))) + .withMessage("AsyncWebRequest must not be null"); - try { - manager.startDeferredResultProcessing(new DeferredResult()); - fail("Expected exception"); - } - catch (IllegalStateException ex) { - assertEquals("AsyncWebRequest must not be null", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + manager.startDeferredResultProcessing(new DeferredResult())) + .withMessage("AsyncWebRequest must not be null"); } @Test @@ -98,10 +92,11 @@ public class WebAsyncManagerTests { assertTrue(this.asyncManager.isConcurrentHandlingStarted()); } - @Test(expected = IllegalArgumentException.class) + @Test public void setAsyncWebRequestAfterAsyncStarted() { this.asyncWebRequest.startAsync(); - this.asyncManager.setAsyncWebRequest(null); + assertThatIllegalArgumentException().isThrownBy(() -> + this.asyncManager.setAsyncWebRequest(null)); } @Test @@ -148,7 +143,6 @@ public class WebAsyncManagerTests { verify(interceptor).postProcess(this.asyncWebRequest, task, concurrentResult); } - @SuppressWarnings("unchecked") @Test public void startCallableProcessingBeforeConcurrentHandlingException() throws Exception { Callable task = new StubCallable(21); @@ -159,13 +153,9 @@ public class WebAsyncManagerTests { this.asyncManager.registerCallableInterceptor("interceptor", interceptor); - try { - this.asyncManager.startCallableProcessing(task); - fail("Expected Exception"); - } - catch (Exception ex) { - assertEquals(exception, ex); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + this.asyncManager.startCallableProcessing(task)) + .isEqualTo(exception); assertFalse(this.asyncManager.hasConcurrentResult()); @@ -259,13 +249,9 @@ public class WebAsyncManagerTests { @Test public void startCallableProcessingNullInput() throws Exception { - try { - this.asyncManager.startCallableProcessing((Callable) null); - fail("Expected exception"); - } - catch (IllegalArgumentException ex) { - assertEquals("Callable must not be null", ex.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.asyncManager.startCallableProcessing((Callable) null)) + .withMessage("Callable must not be null"); } @Test @@ -290,7 +276,6 @@ public class WebAsyncManagerTests { verify(this.asyncWebRequest).setTimeout(1000L); } - @SuppressWarnings("unchecked") @Test public void startDeferredResultProcessingBeforeConcurrentHandlingException() throws Exception { DeferredResult deferredResult = new DeferredResult<>(); @@ -301,13 +286,9 @@ public class WebAsyncManagerTests { this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); - try { - this.asyncManager.startDeferredResultProcessing(deferredResult); - fail("Expected Exception"); - } - catch (Exception success) { - assertEquals(exception, success); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + this.asyncManager.startDeferredResultProcessing(deferredResult)) + .isEqualTo(exception); assertFalse(this.asyncManager.hasConcurrentResult()); @@ -360,13 +341,9 @@ public class WebAsyncManagerTests { @Test public void startDeferredResultProcessingNullInput() throws Exception { - try { - this.asyncManager.startDeferredResultProcessing(null); - fail("Expected exception"); - } - catch (IllegalArgumentException ex) { - assertEquals("DeferredResult must not be null", ex.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.asyncManager.startDeferredResultProcessing(null)) + .withMessage("DeferredResult must not be null"); } private void setupDefaultAsyncScenario() { @@ -374,7 +351,6 @@ public class WebAsyncManagerTests { given(this.asyncWebRequest.isAsyncComplete()).willReturn(false); } - @SuppressWarnings("unchecked") private void verifyDefaultAsyncScenario() { verify(this.asyncWebRequest).addTimeoutHandler(notNull()); verify(this.asyncWebRequest).addErrorHandler(notNull()); diff --git a/spring-web/src/test/java/org/springframework/web/context/support/Spr8510Tests.java b/spring-web/src/test/java/org/springframework/web/context/support/Spr8510Tests.java index f44d4373582..07a57e521cf 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/Spr8510Tests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/Spr8510Tests.java @@ -25,8 +25,7 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.ContextLoaderListener; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests the interaction between a WebApplicationContext and ContextLoaderListener with @@ -47,15 +46,9 @@ public class Spr8510Tests { MockServletContext sc = new MockServletContext(); - try { - cll.contextInitialized(new ServletContextEvent(sc)); - fail("expected exception"); - } - catch (Throwable t) { - // assert that an attempt was made to load the correct XML - assertTrue(t.getMessage(), t.getMessage().endsWith( - "Could not open ServletContext resource [/programmatic.xml]")); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + cll.contextInitialized(new ServletContextEvent(sc))) + .withMessageEndingWith("Could not open ServletContext resource [/programmatic.xml]"); } /** @@ -74,15 +67,9 @@ public class Spr8510Tests { MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); - try { - cll.contextInitialized(new ServletContextEvent(sc)); - fail("expected exception"); - } - catch (Throwable t) { - // assert that an attempt was made to load the correct XML - assertTrue(t.getMessage(), t.getMessage().endsWith( - "Could not open ServletContext resource [/from-init-param.xml]")); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + cll.contextInitialized(new ServletContextEvent(sc))) + .withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]"); } /** @@ -98,15 +85,9 @@ public class Spr8510Tests { MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); - try { - cll.contextInitialized(new ServletContextEvent(sc)); - fail("expected exception"); - } - catch (Throwable t) { - // assert that an attempt was made to load the correct XML - assertTrue(t.getMessage().endsWith( - "Could not open ServletContext resource [/from-init-param.xml]")); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + cll.contextInitialized(new ServletContextEvent(sc))) + .withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]"); } /** @@ -126,16 +107,9 @@ public class Spr8510Tests { MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); - try { - cll.contextInitialized(new ServletContextEvent(sc)); - fail("expected exception"); - } - catch (Throwable t) { - // assert that an attempt was made to load the correct XML - System.out.println(t.getMessage()); - assertTrue(t.getMessage().endsWith( - "Could not open ServletContext resource [/from-init-param.xml]")); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + cll.contextInitialized(new ServletContextEvent(sc))) + .withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]"); } /** @@ -152,16 +126,9 @@ public class Spr8510Tests { // no init-param set //sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); - try { - cll.contextInitialized(new ServletContextEvent(sc)); - fail("expected exception"); - } - catch (Throwable t) { - // assert that an attempt was made to load the correct XML - System.out.println(t.getMessage()); - assertTrue(t.getMessage().endsWith( - "Could not open ServletContext resource [/WEB-INF/applicationContext.xml]")); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + cll.contextInitialized(new ServletContextEvent(sc))) + .withMessageEndingWith("Could not open ServletContext resource [/WEB-INF/applicationContext.xml]"); } /** diff --git a/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java b/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java index cba692307cd..f028da1e816 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java @@ -24,6 +24,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -72,16 +73,18 @@ public class CorsConfigurationTests { assertEquals(new Long(123), config.getMaxAge()); } - @Test(expected = IllegalArgumentException.class) + @Test public void asteriskWildCardOnAddExposedHeader() { CorsConfiguration config = new CorsConfiguration(); - config.addExposedHeader("*"); + assertThatIllegalArgumentException().isThrownBy(() -> + config.addExposedHeader("*")); } - @Test(expected = IllegalArgumentException.class) + @Test public void asteriskWildCardOnSetExposedHeaders() { CorsConfiguration config = new CorsConfiguration(); - config.setExposedHeaders(Arrays.asList("*")); + assertThatIllegalArgumentException().isThrownBy(() -> + config.setExposedHeaders(Arrays.asList("*"))); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java b/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java index 287d795f340..f4fda927063 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.test.MockHttpServletRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -50,9 +51,10 @@ public class UrlBasedCorsConfigurationSourceTests { assertEquals(config, this.configSource.getCorsConfiguration(request)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void unmodifiableConfigurationsMap() { - this.configSource.getCorsConfigurations().put("/**", new CorsConfiguration()); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + this.configSource.getCorsConfigurations().put("/**", new CorsConfiguration())); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java b/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java index 6749ba185f5..7b45e97747c 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java @@ -34,6 +34,7 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -174,7 +175,7 @@ public class DelegatingFilterProxyTests { assertNull(targetFilter.filterConfig); } - @Test(expected = IllegalStateException.class) + @Test public void testDelegatingFilterProxyWithTargetBeanNameAndNoApplicationContext() throws ServletException, IOException { @@ -185,7 +186,8 @@ public class DelegatingFilterProxyTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - filterProxy.doFilter(request, response, null); // throws + assertThatIllegalStateException().isThrownBy(() -> + filterProxy.doFilter(request, response, null)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java index a5e5589a36e..8c9afed854b 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java @@ -29,6 +29,7 @@ import org.springframework.mock.web.test.MockFilterChain; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; @@ -45,14 +46,16 @@ public class RelativeRedirectFilterTests { private HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - @Test(expected = IllegalArgumentException.class) + @Test public void sendRedirectHttpStatusWhenNullThenIllegalArgumentException() { - this.filter.setRedirectStatus(null); + assertThatIllegalArgumentException().isThrownBy(() -> + this.filter.setRedirectStatus(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void sendRedirectHttpStatusWhenNot3xxThenIllegalArgumentException() { - this.filter.setRedirectStatus(HttpStatus.OK); + assertThatIllegalArgumentException().isThrownBy(() -> + this.filter.setRedirectStatus(HttpStatus.OK)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java index 3834f29ca90..57d91abed1c 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java @@ -31,10 +31,11 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -84,21 +85,14 @@ public class RequestContextFilterTests { try { rbf.doFilter(req, resp, fc); - if (sex != null) { - fail(); - } + assertThat(sex).isNull(); } catch (ServletException ex) { assertNotNull(sex); } - try { - RequestContextHolder.currentRequestAttributes(); - fail(); - } - catch (IllegalStateException ex) { - // Ok - } + assertThatIllegalStateException().isThrownBy( + RequestContextHolder::currentRequestAttributes); assertEquals(1, fc.invocations); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java index 69b209f4acf..2886ba56114 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java @@ -31,10 +31,10 @@ import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test fixture with {@link org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver}. @@ -86,10 +86,10 @@ public class CookieValueMethodArgumentResolverTests { assertEquals("Invalid result", "bar", result); } - @Test(expected = ServletRequestBindingException.class) + @Test public void notFound() throws Exception { - resolver.resolveArgument(paramNamedCookie, null, webRequest, null); - fail("Expected exception"); + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + resolver.resolveArgument(paramNamedCookie, null, webRequest, null)); } private static class TestCookieValueMethodArgumentResolver extends AbstractCookieValueMethodArgumentResolver { diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java index 442ae8ae308..e88c5e44def 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java @@ -28,6 +28,7 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertSame; /** @@ -73,18 +74,20 @@ public class ErrorsMethodArgumentResolverTests { assertSame(actual, bindingResult); } - @Test(expected = IllegalStateException.class) + @Test public void bindingResultNotFound() throws Exception { ModelAndViewContainer mavContainer = new ModelAndViewContainer(); mavContainer.addAllAttributes(bindingResult.getModel()); mavContainer.addAttribute("ignore1", "value1"); - resolver.resolveArgument(paramErrors, mavContainer, webRequest, null); + assertThatIllegalStateException().isThrownBy(() -> + resolver.resolveArgument(paramErrors, mavContainer, webRequest, null)); } - @Test(expected = IllegalStateException.class) + @Test public void noBindingResult() throws Exception { - resolver.resolveArgument(paramErrors, new ModelAndViewContainer(), webRequest, null); + assertThatIllegalStateException().isThrownBy(() -> + resolver.resolveArgument(paramErrors, new ModelAndViewContainer(), webRequest, null)); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java index 498cf1c8634..246d6998eb9 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java @@ -29,6 +29,7 @@ import org.springframework.stereotype.Controller; import org.springframework.util.ClassUtils; import org.springframework.web.bind.annotation.ExceptionHandler; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -84,14 +85,16 @@ public class ExceptionHandlerMethodResolverTests { assertEquals("handleIOException", resolver.resolveMethod(exception).getName()); } - @Test(expected = IllegalStateException.class) + @Test public void ambiguousExceptionMapping() { - new ExceptionHandlerMethodResolver(AmbiguousController.class); + assertThatIllegalStateException().isThrownBy(() -> + new ExceptionHandlerMethodResolver(AmbiguousController.class)); } - @Test(expected = IllegalStateException.class) + @Test public void noExceptionMapping() { - new ExceptionHandlerMethodResolver(NoExceptionController.class); + assertThatIllegalStateException().isThrownBy(() -> + new ExceptionHandlerMethodResolver(NoExceptionController.class)); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java index 94c31bb3f75..04a6aeecf76 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java @@ -36,6 +36,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite; import org.springframework.web.method.support.InvocableHandlerMethod; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -102,10 +103,11 @@ public class InitBinderDataBinderFactoryTests { assertNull(dataBinder.getDisallowedFields()); } - @Test(expected = IllegalStateException.class) + @Test public void returnValueNotExpected() throws Exception { WebDataBinderFactory factory = createFactory("initBinderReturnValue", WebDataBinder.class); - factory.createBinder(this.webRequest, null, "invalidName"); + assertThatIllegalStateException().isThrownBy(() -> + factory.createBinder(this.webRequest, null, "invalidName")); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java index 5c072fe567d..31dc4da81b4 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java @@ -45,6 +45,7 @@ import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -216,7 +217,7 @@ public class ModelAttributeMethodProcessorTests { assertTrue(dataBinder.isValidateInvoked()); } - @Test(expected = BindException.class) + @Test public void resolveArgumentBindException() throws Exception { String name = "testBean"; Object target = new TestBean(); @@ -227,7 +228,8 @@ public class ModelAttributeMethodProcessorTests { WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); given(binderFactory.createBinder(this.request, target, name)).willReturn(dataBinder); - this.processor.resolveArgument(this.paramNonSimpleType, this.container, this.request, binderFactory); + assertThatExceptionOfType(BindException.class).isThrownBy(() -> + this.processor.resolveArgument(this.paramNonSimpleType, this.container, this.request, binderFactory)); verify(binderFactory).createBinder(this.request, target, name); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java index d4d0a1b5af6..a28e724f5af 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java @@ -41,11 +41,11 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolverCompo import org.springframework.web.method.support.InvocableHandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -153,13 +153,8 @@ public class ModelFactoryTests { public void sessionAttributeNotPresent() throws Exception { ModelFactory modelFactory = new ModelFactory(null, null, this.attributeHandler); HandlerMethod handlerMethod = createHandlerMethod("handleSessionAttr", String.class); - try { - modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - fail("Expected HttpSessionRequiredException"); - } - catch (HttpSessionRequiredException ex) { - // expected - } + assertThatExceptionOfType(HttpSessionRequiredException.class).isThrownBy(() -> + modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod)); // Now add attribute and try again this.attributeStore.storeAttribute(this.webRequest, "sessionAttr", "sessionAttrValue"); diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java index 4d1a70fdaa1..51b4f878e38 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java @@ -41,6 +41,7 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.support.GenericWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -190,9 +191,10 @@ public class RequestHeaderMethodArgumentResolverTests { assertEquals("/bar", result); } - @Test(expected = ServletRequestBindingException.class) + @Test public void notFound() throws Exception { - resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null); + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java index a4d4f55e748..b42d89fb923 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java @@ -47,12 +47,12 @@ import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.MissingServletRequestPartException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; @@ -305,11 +305,11 @@ public class RequestParamMethodArgumentResolverTests { assertEquals(Arrays.asList(expected1, expected2), result); } - @Test(expected = MultipartException.class) + @Test public void isMultipartRequest() throws Exception { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class); - resolver.resolveArgument(param, null, webRequest, null); - fail("Expected exception: request is not a multipart request"); + assertThatExceptionOfType(MultipartException.class).isThrownBy(() -> + resolver.resolveArgument(param, null, webRequest, null)); } @Test // SPR-9079 @@ -328,21 +328,21 @@ public class RequestParamMethodArgumentResolverTests { assertEquals(expected, ((List) actual).get(0)); } - @Test(expected = MultipartException.class) + @Test public void noMultipartContent() throws Exception { request.setMethod("POST"); MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class); - resolver.resolveArgument(param, null, webRequest, null); - fail("Expected exception: no multipart content"); + assertThatExceptionOfType(MultipartException.class).isThrownBy(() -> + resolver.resolveArgument(param, null, webRequest, null)); } - @Test(expected = MissingServletRequestPartException.class) + @Test public void missingMultipartFile() throws Exception { request.setMethod("POST"); request.setContentType("multipart/form-data"); MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class); - resolver.resolveArgument(param, null, webRequest, null); - fail("Expected exception: no such part found"); + assertThatExceptionOfType(MissingServletRequestPartException.class).isThrownBy(() -> + resolver.resolveArgument(param, null, webRequest, null)); } @Test @@ -368,11 +368,11 @@ public class RequestParamMethodArgumentResolverTests { assertEquals("Invalid result", "bar", result); } - @Test(expected = MissingServletRequestParameterException.class) + @Test public void missingRequestParam() throws Exception { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class); - resolver.resolveArgument(param, null, webRequest, null); - fail("Expected exception"); + assertThatExceptionOfType(MissingServletRequestParameterException.class).isThrownBy(() -> + resolver.resolveArgument(param, null, webRequest, null)); } @Test // SPR-10578 diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java index 432930c65cb..eed9572900f 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java @@ -27,6 +27,8 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -111,25 +113,28 @@ public class WebArgumentResolverAdapterTests { assertEquals("Invalid result", expected, result); } - @Test(expected = IllegalStateException.class) + @Test public void resolveArgumentUnresolved() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willReturn(WebArgumentResolver.UNRESOLVED); - adapter.resolveArgument(parameter, null, webRequest, null); + assertThatIllegalStateException().isThrownBy(() -> + adapter.resolveArgument(parameter, null, webRequest, null)); } - @Test(expected = IllegalStateException.class) + @Test public void resolveArgumentWrongType() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willReturn("Foo"); - adapter.resolveArgument(parameter, null, webRequest, null); + assertThatIllegalStateException().isThrownBy(() -> + adapter.resolveArgument(parameter, null, webRequest, null)); } - @Test(expected = Exception.class) + @Test public void resolveArgumentThrowsException() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willThrow(new Exception()); - adapter.resolveArgument(parameter, null, webRequest, null); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + adapter.resolveArgument(parameter, null, webRequest, null)); } public void handle(int param) { diff --git a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java index e21b71b5c84..49b2dcc67a3 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -76,9 +77,10 @@ public class HandlerMethodArgumentResolverCompositeTests { assertEquals("Didn't use the first registered resolver", 1, resolvedValue); } - @Test(expected = IllegalArgumentException.class) + @Test public void noSuitableArgumentResolver() throws Exception { - this.resolverComposite.resolveArgument(paramStr, null, null, null); + assertThatIllegalArgumentException().isThrownBy(() -> + this.resolverComposite.resolveArgument(paramStr, null, null, null)); } diff --git a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java index e65b3ad97a8..388c251f1dd 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; @@ -108,9 +109,10 @@ public class HandlerMethodReturnValueHandlerCompositeTests { verifyNoMoreInteractions(responseBodyHandler); } - @Test(expected = IllegalArgumentException.class) + @Test public void noSuitableReturnValueHandler() throws Exception { - this.handlers.handleReturnValue("value", this.stringType, null, null); + assertThatIllegalArgumentException().isThrownBy(() -> + this.handlers.handleReturnValue("value", this.stringType, null, null)); } diff --git a/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java b/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java index a56f874344e..cca464308c5 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java @@ -29,13 +29,11 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.ResolvableMethod; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link InvocableHandlerMethod}. @@ -83,13 +81,9 @@ public class InvocableHandlerMethodTests { @Test public void cannotResolveArg() throws Exception { - try { - getInvocable(Integer.class, String.class).invokeForRequest(request, null); - fail("Expected exception"); - } - catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("Could not resolve parameter [0]")); - } + assertThatIllegalStateException().isThrownBy(() -> + getInvocable(Integer.class, String.class).invokeForRequest(request, null)) + .withMessageContaining("Could not resolve parameter [0]"); } @Test @@ -113,85 +107,54 @@ public class InvocableHandlerMethodTests { @Test public void exceptionInResolvingArg() throws Exception { this.composite.addResolver(new ExceptionRaisingArgumentResolver()); - try { - getInvocable(Integer.class, String.class).invokeForRequest(request, null); - fail("Expected exception"); - } - catch (IllegalArgumentException ex) { - // expected - allow HandlerMethodArgumentResolver exceptions to propagate - } + assertThatIllegalArgumentException().isThrownBy(() -> + getInvocable(Integer.class, String.class).invokeForRequest(request, null)); } @Test public void illegalArgumentException() throws Exception { this.composite.addResolver(new StubArgumentResolver(Integer.class, "__not_an_int__")); this.composite.addResolver(new StubArgumentResolver("value")); - try { - getInvocable(Integer.class, String.class).invokeForRequest(request, null); - fail("Expected exception"); - } - catch (IllegalStateException ex) { - assertNotNull("Exception not wrapped", ex.getCause()); - assertTrue(ex.getCause() instanceof IllegalArgumentException); - assertTrue(ex.getMessage().contains("Controller [")); - assertTrue(ex.getMessage().contains("Method [")); - assertTrue(ex.getMessage().contains("with argument values:")); - assertTrue(ex.getMessage().contains("[0] [type=java.lang.String] [value=__not_an_int__]")); - assertTrue(ex.getMessage().contains("[1] [type=java.lang.String] [value=value")); - } + assertThatIllegalStateException().isThrownBy(() -> + getInvocable(Integer.class, String.class).invokeForRequest(request, null)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Controller [") + .withMessageContaining("Method [") + .withMessageContaining("with argument values:") + .withMessageContaining("[0] [type=java.lang.String] [value=__not_an_int__]") + .withMessageContaining("[1] [type=java.lang.String] [value=value"); } @Test public void invocationTargetException() throws Exception { - Throwable expected = new RuntimeException("error"); - try { - getInvocable(Throwable.class).invokeForRequest(this.request, null, expected); - fail("Expected exception"); - } - catch (RuntimeException actual) { - assertSame(expected, actual); - } + RuntimeException runtimeException = new RuntimeException("error"); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> + getInvocable(Throwable.class).invokeForRequest(this.request, null, runtimeException)) + .isSameAs(runtimeException); - expected = new Error("error"); - try { - getInvocable(Throwable.class).invokeForRequest(this.request, null, expected); - fail("Expected exception"); - } - catch (Error actual) { - assertSame(expected, actual); - } + Error error = new Error("error"); + assertThatExceptionOfType(Error.class).isThrownBy(() -> + getInvocable(Throwable.class).invokeForRequest(this.request, null, error)) + .isSameAs(error); - expected = new Exception("error"); - try { - getInvocable(Throwable.class).invokeForRequest(this.request, null, expected); - fail("Expected exception"); - } - catch (Exception actual) { - assertSame(expected, actual); - } + Exception exception = new Exception("error"); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> + getInvocable(Throwable.class).invokeForRequest(this.request, null, exception)) + .isSameAs(exception); - expected = new Throwable("error"); - try { - getInvocable(Throwable.class).invokeForRequest(this.request, null, expected); - fail("Expected exception"); - } - catch (IllegalStateException actual) { - assertNotNull(actual.getCause()); - assertSame(expected, actual.getCause()); - assertTrue(actual.getMessage().contains("Invocation failure")); - } + Throwable throwable = new Throwable("error"); + assertThatIllegalStateException().isThrownBy(() -> + getInvocable(Throwable.class).invokeForRequest(this.request, null, throwable)) + .withCause(throwable) + .withMessageContaining("Invocation failure"); } @Test // SPR-13917 public void invocationErrorMessage() throws Exception { this.composite.addResolver(new StubArgumentResolver(double.class)); - try { - getInvocable(double.class).invokeForRequest(this.request, null); - fail(); - } - catch (IllegalStateException ex) { - assertThat(ex.getMessage(), containsString("Illegal argument")); - } + assertThatIllegalStateException().isThrownBy(() -> + getInvocable(double.class).invokeForRequest(this.request, null)) + .withMessageContaining("Illegal argument"); } private InvocableHandlerMethod getInvocable(Class... argTypes) { diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java index d5b78069d6c..d66297c51b0 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java @@ -22,6 +22,7 @@ import org.junit.Test; import org.springframework.web.multipart.MultipartFile; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -77,11 +78,12 @@ public class ByteArrayMultipartFileEditorTests { assertEquals(expectedValue, editor.getAsText()); } - @Test(expected = IllegalArgumentException.class) + @Test public void setValueAsMultipartFileWithBadBytes() throws Exception { MultipartFile file = mock(MultipartFile.class); given(file.getBytes()).willThrow(new IOException()); - editor.setValue(file); + assertThatIllegalArgumentException().isThrownBy(() -> + editor.setValue(file)); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java b/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java index 8a0ac748d59..26fe7f2b725 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java @@ -25,6 +25,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.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -106,11 +107,10 @@ public class HeaderWebSessionIdResolverTests { this.exchange.getResponse().getHeaders().get(headerName)); } - @Test(expected = IllegalArgumentException.class) + @Test public void setSessionIdWhenNullIdThenIllegalArgumentException() { - String id = null; - - this.idResolver.setSessionId(this.exchange, id); + assertThatIllegalArgumentException().isThrownBy(() -> + this.idResolver.setSessionId(this.exchange, (String) null)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java b/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java index 37bbf772f5a..63762547435 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java @@ -27,12 +27,12 @@ import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; import org.springframework.web.server.WebSession; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link InMemoryWebSessionStore}. @@ -149,14 +149,9 @@ public class InMemoryWebSessionStoreTests { public void maxSessions() { IntStream.range(0, 10000).forEach(i -> insertSession()); - - try { - insertSession(); - fail(); - } - catch (IllegalStateException ex) { - assertEquals("Max sessions limit reached: 10000", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy( + this::insertSession) + .withMessage("Max sessions limit reached: 10000"); } private WebSession insertSession() { diff --git a/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java b/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java index 8cb5aac6126..4a7337aa02e 100644 --- a/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java @@ -21,10 +21,10 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.FileCopyUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; /** * @author Brian Clozel @@ -74,13 +74,9 @@ public class ContentCachingRequestWrapperTests { } }; - try { - FileCopyUtils.copyToByteArray(wrapper.getInputStream()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - assertEquals("3", ex.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> + FileCopyUtils.copyToByteArray(wrapper.getInputStream())) + .withMessage("3"); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java index 870813d0b36..de4a8a5d4ab 100644 --- a/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java @@ -22,6 +22,8 @@ import javax.servlet.jsp.tagext.TagSupport; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -52,24 +54,28 @@ public class TagUtilsTests { TagUtils.getScope("bla")); } - @Test(expected = IllegalArgumentException.class) + @Test public void getScopeWithNullScopeArgument() { - TagUtils.getScope(null); + assertThatIllegalArgumentException().isThrownBy(() -> + TagUtils.getScope(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void hasAncestorOfTypeWhereAncestorTagIsNotATagType() throws Exception { - assertFalse(TagUtils.hasAncestorOfType(new TagSupport(), String.class)); + assertThatIllegalArgumentException().isThrownBy(() -> + TagUtils.hasAncestorOfType(new TagSupport(), String.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void hasAncestorOfTypeWithNullTagArgument() throws Exception { - assertFalse(TagUtils.hasAncestorOfType(null, TagSupport.class)); + assertThatIllegalArgumentException().isThrownBy(() -> + TagUtils.hasAncestorOfType(null, TagSupport.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void hasAncestorOfTypeWithNullAncestorTagClassArgument() throws Exception { - assertFalse(TagUtils.hasAncestorOfType(new TagSupport(), null)); + assertThatIllegalArgumentException().isThrownBy(() -> + TagUtils.hasAncestorOfType(new TagSupport(), null)); } @Test @@ -101,26 +107,29 @@ public class TagUtilsTests { assertFalse(TagUtils.hasAncestorOfType(new TagA(), TagC.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void assertHasAncestorOfTypeWithNullTagName() throws Exception { - TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, null, "c"); + assertThatIllegalArgumentException().isThrownBy(() -> + TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, null, "c")); } - @Test(expected = IllegalArgumentException.class) + @Test public void assertHasAncestorOfTypeWithNullAncestorTagName() throws Exception { - TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, "a", null); + assertThatIllegalArgumentException().isThrownBy(() -> + TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, "a", null)); } - @Test(expected = IllegalStateException.class) + @Test public void assertHasAncestorOfTypeThrowsExceptionOnFail() throws Exception { - Tag a = new TagA(); - Tag b = new TagB(); - Tag anotherB = new TagB(); + Tag a = new TagA(); + Tag b = new TagB(); + Tag anotherB = new TagB(); - a.setParent(b); - b.setParent(anotherB); + a.setParent(b); + b.setParent(anotherB); - TagUtils.assertHasAncestorOfType(a, TagC.class, "a", "c"); + assertThatIllegalStateException().isThrownBy(() -> + TagUtils.assertHasAncestorOfType(a, TagC.class, "a", "c")); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 161040b2d8e..d9186463249 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,6 +33,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +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; @@ -216,9 +217,10 @@ public class UriComponentsBuilderTests { assertEquals("https", UriComponentsBuilder.fromHttpUrl("HTTPS://www.google.com").build().getScheme()); } - @Test(expected = IllegalArgumentException.class) // SPR-10539 + @Test // SPR-10539 public void fromHttpUrlStringInvalidIPv6Host() { - UriComponentsBuilder.fromHttpUrl("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource").build().encode(); + assertThatIllegalArgumentException().isThrownBy(() -> + UriComponentsBuilder.fromHttpUrl("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource").build().encode()); } @Test // SPR-10539 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 44bcf6bd7eb..71d120ccba2 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,6 +27,8 @@ import java.util.Collections; import org.junit.Test; +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; @@ -158,19 +160,22 @@ public class UriComponentsTests { assertEquals("https://example.com:8080/bar", uri4.toUriString()); } - @Test(expected = IllegalStateException.class) + @Test public void expandEncoded() { - UriComponentsBuilder.fromPath("/{foo}").build().encode().expand("bar"); + assertThatIllegalStateException().isThrownBy(() -> + UriComponentsBuilder.fromPath("/{foo}").build().encode().expand("bar")); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidCharacters() { - UriComponentsBuilder.fromPath("/{foo}").build(true); + assertThatIllegalArgumentException().isThrownBy(() -> + UriComponentsBuilder.fromPath("/{foo}").build(true)); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidEncodedSequence() { - UriComponentsBuilder.fromPath("/fo%2o").build(true); + assertThatIllegalArgumentException().isThrownBy(() -> + UriComponentsBuilder.fromPath("/fo%2o").build(true)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java b/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java index d3d0636f306..7e8f5664394 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java @@ -25,6 +25,7 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -59,10 +60,11 @@ public class UriTemplateTests { assertEquals(new URI("/sum?numbers=1,2,3"), result); } - @Test(expected = IllegalArgumentException.class) + @Test public void expandVarArgsNotEnoughVariables() throws Exception { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); - template.expand("1"); + assertThatIllegalArgumentException().isThrownBy(() -> + template.expand("1")); } @Test @@ -101,13 +103,14 @@ public class UriTemplateTests { assertEquals("Invalid expanded template", new URI("/hotel%20list/Z%C3%BCrich"), result); } - @Test(expected = IllegalArgumentException.class) + @Test public void expandMapUnboundVariables() throws Exception { Map uriVariables = new HashMap<>(2); uriVariables.put("booking", "42"); uriVariables.put("bar", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); - template.expand(uriVariables); + assertThatIllegalArgumentException().isThrownBy(() -> + template.expand(uriVariables)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java index 0f7ac273c0b..1fc05ed5491 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java @@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -109,9 +110,10 @@ public class UriUtilsTests { assertEquals("Invalid encoded result", "T\u014dky\u014d", UriUtils.decode("T\u014dky\u014d", CHARSET)); } - @Test(expected = IllegalArgumentException.class) + @Test public void decodeInvalidSequence() { - UriUtils.decode("foo%2", CHARSET); + assertThatIllegalArgumentException().isThrownBy(() -> + UriUtils.decode("foo%2", CHARSET)); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java b/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java index 27d28ef321b..cf4f2e53266 100644 --- a/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java @@ -25,6 +25,9 @@ import org.junit.Test; import org.springframework.http.server.PathContainer; import org.springframework.web.util.pattern.PatternParseException.PatternMessage; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -242,20 +245,12 @@ public class PathPatternParserTests { checkError("/foobar/{abc}_{abc}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE); checkError("/foobar/{abc:..}_{abc:..}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE); PathPattern pp = parse("/{abc:foo(bar)}"); - try { - pp.matchAndExtract(toPSC("/foo")); - fail("Should have raised exception"); - } - catch (IllegalArgumentException iae) { - assertEquals("No capture groups allowed in the constraint regex: foo(bar)", iae.getMessage()); - } - try { - pp.matchAndExtract(toPSC("/foobar")); - fail("Should have raised exception"); - } - catch (IllegalArgumentException iae) { - assertEquals("No capture groups allowed in the constraint regex: foo(bar)", iae.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + pp.matchAndExtract(toPSC("/foo"))) + .withMessage("No capture groups allowed in the constraint regex: foo(bar)"); + assertThatIllegalArgumentException().isThrownBy(() -> + pp.matchAndExtract(toPSC("/foobar"))) + .withMessage("No capture groups allowed in the constraint regex: foo(bar)"); } @Test @@ -432,20 +427,15 @@ public class PathPatternParserTests { private void checkError(String pattern, int expectedPos, PatternMessage expectedMessage, String... expectedInserts) { - try { - pathPattern = parse(pattern); - fail("Expected to fail"); - } - catch (PatternParseException ppe) { - assertEquals(ppe.toDetailedString(), expectedPos, ppe.getPosition()); - assertEquals(ppe.toDetailedString(), expectedMessage, ppe.getMessageType()); + assertThatExceptionOfType(PatternParseException.class).isThrownBy(() -> + pathPattern = parse(pattern)) + .satisfies(ex -> { + assertEquals(ex.toDetailedString(), expectedPos, ex.getPosition()); + assertEquals(ex.toDetailedString(), expectedMessage, ex.getMessageType()); if (expectedInserts.length != 0) { - assertEquals(ppe.getInserts().length, expectedInserts.length); - for (int i = 0; i < expectedInserts.length; i++) { - assertEquals("Insert at position " + i + " is wrong", expectedInserts[i], ppe.getInserts()[i]); - } + assertThat(ex.getInserts()).isEqualTo(expectedInserts); } - } + }); } @SafeVarargs 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 b35f7e20360..dc56016f210 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 @@ -31,6 +31,7 @@ import org.springframework.http.server.PathContainer.Element; import org.springframework.util.AntPathMatcher; 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; @@ -38,7 +39,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Exercise matching of {@link PathPattern} objects. @@ -1180,14 +1180,7 @@ public class PathPatternTests { } for (Map.Entry me : expectedKeyValues.entrySet()) { String value = matchResult.getUriVariables().get(me.getKey()); - if (value == null) { - fail("Did not find key '" + me.getKey() + "' in captured variables: " - + matchResult.getUriVariables()); - } - if (!value.equals(me.getValue())) { - fail("Expected value '" + me.getValue() + "' for key '" + me.getKey() - + "' but was '" + value + "'"); - } + assertThat(value).as("value for " + me.getKey()).isEqualTo(me.getValue()); } return matchResult; } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java index 9b58e4c54a2..01441a5ab3a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java @@ -25,6 +25,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.NotAcceptableStatusException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -50,11 +51,12 @@ public class HeaderContentTypeResolverTests { assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString()); } - @Test(expected = NotAcceptableStatusException.class) + @Test public void resolveMediaTypesParseError() throws Exception { String header = "textplain; q=0.5"; - this.resolver.resolveMediaTypes( - MockServerWebExchange.from(MockServerHttpRequest.get("/").header("accept", header))); + assertThatExceptionOfType(NotAcceptableStatusException.class).isThrownBy(() -> + this.resolver.resolveMediaTypes( + MockServerWebExchange.from(MockServerHttpRequest.get("/").header("accept", header)))); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java index bbc259656d6..54f40f3dcd4 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java @@ -27,6 +27,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.NotAcceptableStatusException; import org.springframework.web.server.ServerWebExchange; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; /** @@ -44,12 +45,11 @@ public class ParameterContentTypeResolverTests { assertEquals(RequestedContentTypeResolver.MEDIA_TYPE_ALL_LIST, mediaTypes); } - @Test(expected = NotAcceptableStatusException.class) + @Test public void noMatchForKey() { ParameterContentTypeResolver resolver = new ParameterContentTypeResolver(Collections.emptyMap()); - List mediaTypes = resolver.resolveMediaTypes(createExchange("blah")); - - assertEquals(0, mediaTypes.size()); + assertThatExceptionOfType(NotAcceptableStatusException.class).isThrownBy(() -> + resolver.resolveMediaTypes(createExchange("blah"))); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java index 6bfafc39a7a..8fc483adb9f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java @@ -63,10 +63,10 @@ import org.springframework.mock.http.client.reactive.test.MockClientHttpResponse import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT; /** @@ -434,12 +434,8 @@ public class BodyExtractorsTests { }) .expectErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnsupportedMediaTypeException); - try { - buffer.release(); - fail("releasing the buffer should have failed"); - } - catch (IllegalReferenceCountException exc) { - } + assertThatExceptionOfType(IllegalReferenceCountException.class).isThrownBy( + buffer::release); body.assertCancelled(); }).verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java index 1e2703fc1ac..905d1642dd9 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java @@ -46,9 +46,9 @@ import org.springframework.http.codec.HttpMessageReader; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.web.reactive.function.BodyExtractors.toMono; @@ -247,13 +247,8 @@ public class DefaultClientResponseTests { ResponseEntity result = defaultClientResponse.toEntity(String.class).block(); assertEquals("foo", result.getBody()); - try { - result.getStatusCode(); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // do nothing - } + assertThatIllegalArgumentException().isThrownBy( + result::getStatusCode); assertEquals(999, result.getStatusCodeValue()); assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); } @@ -318,13 +313,8 @@ public class DefaultClientResponseTests { ResponseEntity> result = defaultClientResponse.toEntityList(String.class).block(); assertEquals(Collections.singletonList("foo"), result.getBody()); - try { - result.getStatusCode(); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // do nothing - } + assertThatIllegalArgumentException().isThrownBy( + result::getStatusCode); assertEquals(999, result.getStatusCodeValue()); assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java index ee61fdb78dd..ae15ab348e0 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java @@ -34,6 +34,7 @@ import org.springframework.core.NamedThreadLocal; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -179,12 +180,13 @@ public class DefaultWebClientTests { assertEquals("bar", actual.get("foo")); } - @Test(expected = IllegalArgumentException.class) + @Test public void bodyObjectPublisher() { Mono mono = Mono.empty(); WebClient client = this.builder.build(); - client.post().uri("https://example.com").syncBody(mono); + assertThatIllegalArgumentException().isThrownBy(() -> + client.post().uri("https://example.com").syncBody(mono)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java index ee2cd1e62c4..2516dbc5179 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java @@ -33,6 +33,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.BodyExtractors; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -115,12 +116,13 @@ public class ExchangeFilterFunctionsTests { assertEquals(response, result); } - @Test(expected = IllegalArgumentException.class) + @Test public void basicAuthenticationInvalidCharacters() { ClientRequest request = ClientRequest.create(HttpMethod.GET, DEFAULT_URL).build(); ExchangeFunction exchange = r -> Mono.just(mock(ClientResponse.class)); - ExchangeFilterFunctions.basicAuthentication("foo", "\ud83d\udca9").filter(request, exchange); + assertThatIllegalArgumentException().isThrownBy(() -> + ExchangeFilterFunctions.basicAuthentication("foo", "\ud83d\udca9").filter(request, exchange)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java index 40f89dd23f4..35fcd2fb9d6 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java @@ -56,6 +56,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.UnsupportedMediaTypeStatusException; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.web.reactive.function.BodyExtractors.toMono; @@ -157,7 +158,7 @@ public class DefaultServerRequestTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void pathVariableNotFound() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.com")); Map pathVariables = Collections.singletonMap("foo", "bar"); @@ -165,7 +166,8 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders); - request.pathVariable("baz"); + assertThatIllegalArgumentException().isThrownBy(() -> + request.pathVariable("baz")); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java index c9280b53c5b..0293dfea4b9 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java @@ -44,6 +44,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.result.view.ViewResolver; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -355,11 +356,12 @@ public class DefaultServerResponseBuilderTests { StepVerifier.create(response.getBody()).expectComplete().verify(); } - @Test(expected = IllegalArgumentException.class) + @Test public void bodyObjectPublisher() { Mono mono = Mono.empty(); - ServerResponse.ok().syncBody(mono); + assertThatIllegalArgumentException().isThrownBy(() -> + ServerResponse.ok().syncBody(mono)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java index 2bbca3264ec..d9b63830fc6 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java @@ -19,6 +19,7 @@ package org.springframework.web.reactive.resource; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -43,9 +44,10 @@ public class FixedVersionStrategyTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void emptyPrefixVersion() { - new FixedVersionStrategy(" "); + assertThatIllegalArgumentException().isThrownBy(() -> + new FixedVersionStrategy(" ")); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java index 5210f13099d..73aee892546 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,6 +55,8 @@ 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.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; @@ -453,17 +455,19 @@ public class ResourceWebHandlerTests { }).verify(TIMEOUT); } - @Test(expected = IllegalArgumentException.class) + @Test public void noPathWithinHandlerMappingAttribute() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); - this.handler.handle(exchange).block(TIMEOUT); + assertThatIllegalArgumentException().isThrownBy(() -> + this.handler.handle(exchange).block(TIMEOUT)); } - @Test(expected = MethodNotAllowedException.class) + @Test public void unsupportedHttpMethod() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("")); setPathWithinHandlerMapping(exchange, "foo.css"); - this.handler.handle(exchange).block(TIMEOUT); + assertThatExceptionOfType(MethodNotAllowedException.class).isThrownBy(() -> + this.handler.handle(exchange).block(TIMEOUT)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java index 3bbcf533c8b..e807d988e47 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java @@ -23,6 +23,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -74,11 +75,12 @@ public class CompositeRequestConditionTests { assertSame(notEmpty, empty.combine(notEmpty)); } - @Test(expected = IllegalArgumentException.class) + @Test public void combineDifferentLength() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1); - cond1.combine(cond2); + assertThatIllegalArgumentException().isThrownBy(() -> + cond1.combine(cond2)); } @Test @@ -128,11 +130,12 @@ public class CompositeRequestConditionTests { assertEquals(1, empty.compareTo(notEmpty, exchange)); } - @Test(expected = IllegalArgumentException.class) + @Test public void compareDifferentLength() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1); - cond1.compareTo(cond2, MockServerWebExchange.from(MockServerHttpRequest.get("/"))); + assertThatIllegalArgumentException().isThrownBy(() -> + cond1.compareTo(cond2, MockServerWebExchange.from(MockServerHttpRequest.get("/")))); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java index c73936ce18b..dd41b1fbab6 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java @@ -22,6 +22,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -56,11 +57,12 @@ public class RequestConditionHolderTests { assertSame(notEmpty, empty.combine(notEmpty)); } - @Test(expected = ClassCastException.class) + @Test public void combineIncompatible() { RequestConditionHolder params = new RequestConditionHolder(new ParamsRequestCondition("name")); RequestConditionHolder headers = new RequestConditionHolder(new HeadersRequestCondition("name")); - params.combine(headers); + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + params.combine(headers)); } @Test @@ -108,11 +110,12 @@ public class RequestConditionHolderTests { assertEquals(1, empty.compareTo(notEmpty, this.exchange)); } - @Test(expected = ClassCastException.class) + @Test public void compareIncompatible() { RequestConditionHolder params = new RequestConditionHolder(new ParamsRequestCondition("name")); RequestConditionHolder headers = new RequestConditionHolder(new HeadersRequestCondition("name")); - params.compareTo(headers, this.exchange); + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + params.compareTo(headers, this.exchange)); } 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 9fdda9df468..f7ddeb14c72 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,6 +35,7 @@ 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.assertThatIllegalStateException; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -66,10 +67,11 @@ public class HandlerMethodMappingTests { } - @Test(expected = IllegalStateException.class) + @Test public void registerDuplicates() { this.mapping.registerMapping("foo", this.handler, this.method1); - this.mapping.registerMapping("foo", this.handler, this.method2); + assertThatIllegalStateException().isThrownBy(() -> + this.mapping.registerMapping("foo", this.handler, this.method2)); } @Test 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 1fb15f28fbe..1c147864f4a 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,13 +42,12 @@ 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.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.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -96,15 +95,9 @@ public class InvocableHandlerMethodTests { public void cannotResolveArg() { Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method(); Mono mono = invoke(new TestController(), method); - - try { - mono.block(); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException ex) { - assertThat(ex.getMessage(), is("Could not resolve parameter [0] in " + - method.toGenericString() + ": No suitable resolver")); - } + assertThatIllegalStateException().isThrownBy( + mono::block) + .withMessage("Could not resolve parameter [0] in " + method.toGenericString() + ": No suitable resolver"); } @Test @@ -130,13 +123,9 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method(); Mono mono = invoke(new TestController(), method); - try { - mono.block(); - fail("Expected UnsupportedMediaTypeStatusException"); - } - catch (UnsupportedMediaTypeStatusException ex) { - assertThat(ex.getMessage(), is("415 UNSUPPORTED_MEDIA_TYPE \"boo\"")); - } + assertThatExceptionOfType(UnsupportedMediaTypeStatusException.class).isThrownBy( + mono::block) + .withMessage("415 UNSUPPORTED_MEDIA_TYPE \"boo\""); } @Test @@ -144,19 +133,13 @@ public class InvocableHandlerMethodTests { this.resolvers.add(stubResolver(1)); Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method(); Mono mono = invoke(new TestController(), method); - - try { - mono.block(); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException ex) { - assertNotNull("Exception not wrapped", ex.getCause()); - assertTrue(ex.getCause() instanceof IllegalArgumentException); - assertTrue(ex.getMessage().contains("Controller [")); - assertTrue(ex.getMessage().contains("Method [")); - assertTrue(ex.getMessage().contains("with argument values:")); - assertTrue(ex.getMessage().contains("[0] [type=java.lang.Integer] [value=1]")); - } + assertThatIllegalStateException().isThrownBy( + mono::block) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Controller [") + .withMessageContaining("Method [") + .withMessageContaining("with argument values:") + .withMessageContaining("[0] [type=java.lang.Integer] [value=1]"); } @Test @@ -164,13 +147,9 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(TestController::exceptionMethod).method(); Mono mono = invoke(new TestController(), method); - try { - mono.block(); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException ex) { - assertThat(ex.getMessage(), is("boo")); - } + assertThatIllegalStateException().isThrownBy( + mono::block) + .withMessage("boo"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java index 89cc820c91e..dd26fd5837f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java @@ -35,10 +35,10 @@ import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test fixture with {@link CookieValueMethodArgumentResolver}. @@ -84,15 +84,9 @@ public class CookieValueMethodArgumentResolverTests { @Test public void doesNotSupportParameter() { assertFalse(this.resolver.supportsParameter(this.stringParameter)); - try { - this.resolver.supportsParameter(this.cookieMonoParameter); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "CookieValueMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.cookieMonoParameter)) + .withMessageStartingWith("CookieValueMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java index a1534cb48f0..341ae7f794d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java @@ -31,10 +31,10 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.ReflectionUtils; import org.springframework.web.reactive.BindingContext; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link ExpressionValueMethodArgumentResolver}. @@ -75,15 +75,9 @@ public class ExpressionValueMethodArgumentResolverTests { @Test public void doesNotSupport() { assertFalse(this.resolver.supportsParameter(this.paramNotSupported)); - try { - this.resolver.supportsParameter(this.paramAlsoNotSupported); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "ExpressionValueMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.paramAlsoNotSupported)) + .withMessageStartingWith("ExpressionValueMethodArgumentResolver does not support reactive type wrapper"); } @Test 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 105881eb83e..f36d187abe2 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 @@ -36,11 +36,12 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.config.CorsRegistry; 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; -import static org.junit.Assert.fail; /** * @@ -88,13 +89,9 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte @Test public void actualRequestWithCorsRejected() throws Exception { - try { - performGet("/cors-restricted", this.headers, String.class); - fail(); - } - catch (HttpClientErrorException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); - } + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + performGet("/cors-restricted", this.headers, String.class)) + .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN)); } @Test @@ -125,26 +122,18 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte @Test public void preFlightRequestWithCorsRejected() throws Exception { - try { - this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); - performOptions("/cors-restricted", this.headers, String.class); - fail(); - } - catch (HttpClientErrorException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); - } + this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + performOptions("/cors-restricted", this.headers, String.class)) + .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN)); } @Test public void preFlightRequestWithoutCorsEnabled() throws Exception { - try { - this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); - performOptions("/welcome", this.headers, String.class); - fail(); - } - catch (HttpClientErrorException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); - } + this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); + assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> + performOptions("/welcome", this.headers, String.class)) + .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java index 068bfe42250..d520c85b9fb 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java @@ -47,12 +47,12 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.http.MediaType.TEXT_PLAIN; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post; @@ -102,15 +102,9 @@ public class HttpEntityMethodArgumentResolverTests { public void doesNotSupport() { assertFalse(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, String.class))); assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); - try { - this.resolver.supportsParameter(this.testMethod.arg(Mono.class, httpEntityType(String.class))); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "HttpEntityMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.testMethod.arg(Mono.class, httpEntityType(String.class)))) + .withMessageStartingWith("HttpEntityMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java index 4115f3ed029..fda5b3844ce 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java @@ -37,6 +37,7 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver; import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -104,11 +105,12 @@ public class InitBinderBindingContextTests { assertNull(dataBinder.getDisallowedFields()); } - @Test(expected = IllegalStateException.class) + @Test public void returnValueNotExpected() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); BindingContext context = createBindingContext("initBinderReturnValue", WebDataBinder.class); - context.createDataBinder(exchange, null, "invalidName"); + assertThatIllegalStateException().isThrownBy(() -> + context.createDataBinder(exchange, null, "invalidName")); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java index 7ec8d90f34c..391f0c98578 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java @@ -37,6 +37,7 @@ import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.ServerErrorException; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -104,19 +105,21 @@ public class MatrixVariablesMethodArgumentResolverTests { assertEquals(2013, actual); } - @Test(expected = ServerErrorException.class) + @Test public void resolveArgumentMultipleMatches() throws Exception { getVariablesFor("var1").add("colors", "red"); getVariablesFor("var2").add("colors", "green"); MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); - this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); + assertThatExceptionOfType(ServerErrorException.class).isThrownBy(() -> + this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)); } - @Test(expected = ServerWebInputException.class) + @Test public void resolveArgumentRequired() throws Exception { MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); - this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); + assertThatExceptionOfType(ServerWebInputException.class).isThrownBy(() -> + this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java index 57bc4f6bdae..85ab2d28f84 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java @@ -53,9 +53,9 @@ import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** @@ -174,13 +174,9 @@ public class ModelInitializerTests { Method method = ResolvableMethod.on(TestController.class).annotPresent(PostMapping.class).resolveMethod(); HandlerMethod handlerMethod = new HandlerMethod(controller, method); - try { - this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000)); - fail(); - } - catch (IllegalArgumentException ex) { - assertEquals("Required attribute 'missing-bean' is missing.", ex.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000))) + .withMessage("Required attribute 'missing-bean' is missing."); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java index 978ffd66a0a..f537b056ae3 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java @@ -34,10 +34,10 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link PathVariableMapMethodArgumentResolver}. @@ -73,15 +73,9 @@ public class PathVariableMapMethodArgumentResolverTests { assertTrue(resolver.supportsParameter(paramMap)); assertFalse(resolver.supportsParameter(paramNamedMap)); assertFalse(resolver.supportsParameter(paramMapNoAnnot)); - try { - this.resolver.supportsParameter(this.paramMonoMap); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "PathVariableMapMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.paramMonoMap)) + .withMessageStartingWith("PathVariableMapMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java index 4270632054b..e121d2411d7 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java @@ -39,10 +39,10 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.ServerErrorException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link PathVariableMethodArgumentResolver}. @@ -80,15 +80,9 @@ public class PathVariableMethodArgumentResolverTests { public void supportsParameter() { assertTrue(this.resolver.supportsParameter(this.paramNamedString)); assertFalse(this.resolver.supportsParameter(this.paramString)); - try { - this.resolver.supportsParameter(this.paramMono); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "PathVariableMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.paramMono)) + .withMessageStartingWith("PathVariableMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java index fb4de5be921..f35c422e484 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java @@ -45,6 +45,7 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -94,10 +95,11 @@ public class RequestBodyMethodArgumentResolverTests { assertEquals(body, value); } - @Test(expected = ServerWebInputException.class) + @Test public void emptyBodyWithString() { MethodParameter param = this.testMethod.annot(requestBody()).arg(String.class); - resolveValueWithEmptyBody(param); + assertThatExceptionOfType(ServerWebInputException.class).isThrownBy(() -> + resolveValueWithEmptyBody(param)); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java index 8401a9d6254..74ef384197c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java @@ -35,10 +35,10 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.annotation.RequestHeader; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link RequestHeaderMapMethodArgumentResolver}. @@ -76,15 +76,9 @@ public class RequestHeaderMapMethodArgumentResolverTests { assertTrue("MultiValueMap parameter not supported", resolver.supportsParameter(paramMultiValueMap)); assertTrue("HttpHeaders parameter not supported", resolver.supportsParameter(paramHttpHeaders)); assertFalse("non-@RequestParam map supported", resolver.supportsParameter(paramUnsupported)); - try { - this.resolver.supportsParameter(this.paramAlsoUnsupported); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "RequestHeaderMapMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.paramAlsoUnsupported)) + .withMessageStartingWith("RequestHeaderMapMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java index 1bcb912569a..42a9eb76782 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java @@ -41,11 +41,11 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link RequestHeaderMethodArgumentResolver}. @@ -99,15 +99,9 @@ public class RequestHeaderMethodArgumentResolverTests { assertTrue("String parameter not supported", resolver.supportsParameter(paramNamedDefaultValueStringHeader)); assertTrue("String array parameter not supported", resolver.supportsParameter(paramNamedValueStringArray)); assertFalse("non-@RequestParam parameter supported", resolver.supportsParameter(paramNamedValueMap)); - try { - this.resolver.supportsParameter(this.paramMono); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "RequestHeaderMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.paramMono)) + .withMessageStartingWith("RequestHeaderMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java index 869314a6148..3df686f3cd2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java @@ -37,10 +37,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.reactive.config.EnableWebFlux; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * {@code @RequestMapping} integration tests with exception handling scenarios. @@ -81,30 +79,22 @@ public class RequestMappingExceptionHandlingIntegrationTests extends AbstractReq @Test // SPR-16051 public void exceptionAfterSeveralItems() { - try { - performGet("/SPR-16051", new HttpHeaders(), String.class).getBody(); - fail(); - } - catch (Throwable ex) { - String message = ex.getMessage(); - assertNotNull(message); - assertTrue("Actual: " + message, message.startsWith("Error while extracting response")); - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> + performGet("/SPR-16051", new HttpHeaders(), String.class).getBody()) + .withMessageStartingWith("Error while extracting response"); } @Test // SPR-16318 public void exceptionFromMethodWithProducesCondition() throws Exception { - try { - HttpHeaders headers = new HttpHeaders(); - headers.add("Accept", "text/plain, application/problem+json"); - performGet("/SPR-16318", headers, String.class).getBody(); - fail(); - } - catch (HttpStatusCodeException ex) { - assertEquals(500, ex.getRawStatusCode()); - assertEquals("application/problem+json", ex.getResponseHeaders().getContentType().toString()); - assertEquals("{\"reason\":\"error\"}", ex.getResponseBodyAsString()); - } + HttpHeaders headers = new HttpHeaders(); + headers.add("Accept", "text/plain, application/problem+json"); + assertThatExceptionOfType(HttpStatusCodeException.class).isThrownBy(() -> + performGet("/SPR-16318", headers, String.class).getBody()) + .satisfies(ex -> { + assertEquals(500, ex.getRawStatusCode()); + assertEquals("application/problem+json", ex.getResponseHeaders().getContentType().toString()); + assertEquals("{\"reason\":\"error\"}", ex.getResponseBodyAsString()); + }); } private void doTest(String url, String expected) throws Exception { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java index 46aa7646766..3c98d59d206 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java @@ -33,10 +33,10 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.method.ResolvableMethod; import org.springframework.web.server.ServerWebExchange; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; /** @@ -66,16 +66,9 @@ public class RequestParamMapMethodArgumentResolverTests { param = this.testMethod.annotNotPresent(RequestParam.class).arg(Map.class); assertFalse(this.resolver.supportsParameter(param)); - try { - param = this.testMethod.annot(requestParam()).arg(Mono.class, Map.class); - this.resolver.supportsParameter(param); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "RequestParamMapMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.testMethod.annot(requestParam()).arg(Mono.class, Map.class))) + .withMessageStartingWith("RequestParamMapMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java index 6a1a1dc47d6..d9744cc35d5 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java @@ -37,12 +37,12 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; @@ -109,27 +109,12 @@ public class RequestParamMethodArgumentResolverTests { @Test public void doesNotSupportReactiveWrapper() { - MethodParameter param; - try { - param = this.testMethod.annot(requestParam()).arg(Mono.class, String.class); - this.resolver.supportsParameter(param); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "RequestParamMethodArgumentResolver does not support reactive type wrapper")); - } - try { - param = this.testMethod.annotNotPresent(RequestParam.class).arg(Mono.class, String.class); - this.resolver.supportsParameter(param); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "RequestParamMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.testMethod.annot(requestParam()).arg(Mono.class, String.class))) + .withMessageStartingWith("RequestParamMethodArgumentResolver does not support reactive type wrapper"); + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.testMethod.annotNotPresent(RequestParam.class).arg(Mono.class, String.class))) + .withMessageStartingWith("RequestParamMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java index 5a56b68a5a8..b216d2ab7df 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java @@ -37,11 +37,11 @@ import org.springframework.web.server.WebSession; import org.springframework.web.util.UriBuilder; import org.springframework.web.util.UriComponentsBuilder; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link ServerWebExchangeMethodArgumentResolver}. @@ -73,15 +73,9 @@ public class ServerWebExchangeMethodArgumentResolverTests { assertFalse(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class))); assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); - try { - this.resolver.supportsParameter(this.testMethod.arg(Mono.class, ServerWebExchange.class)); - fail(); - } - catch (IllegalStateException ex) { - assertTrue("Unexpected error message:\n" + ex.getMessage(), - ex.getMessage().startsWith( - "ServerWebExchangeMethodArgumentResolver does not support reactive type wrapper")); - } + assertThatIllegalStateException().isThrownBy(() -> + this.resolver.supportsParameter(this.testMethod.arg(Mono.class, ServerWebExchange.class))) + .withMessageStartingWith("ServerWebExchangeMethodArgumentResolver does not support reactive type wrapper"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java index 543778fe0e3..762322abe89 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java @@ -38,9 +38,8 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.ModelMap; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link HttpMessageWriterView}. @@ -107,14 +106,9 @@ public class HttpMessageWriterViewTests { this.model.addAttribute("foo1", "bar1"); this.model.addAttribute("foo2", "bar2"); - try { - doRender(); - fail(); - } - catch (IllegalStateException ex) { - String message = ex.getMessage(); - assertTrue(message, message.contains("Map rendering is not supported")); - } + assertThatIllegalStateException().isThrownBy( + this::doRender) + .withMessageContaining("Map rendering is not supported"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java index eba6cde619d..b7c43a8f916 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java @@ -30,6 +30,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.reactive.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -51,10 +52,11 @@ public class RedirectViewTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void noUrlSet() throws Exception { RedirectView rv = new RedirectView(null); - rv.afterPropertiesSet(); + assertThatIllegalArgumentException().isThrownBy( + rv::afterPropertiesSet); } @Test 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 5d10fe44f6b..a5bb4a04829 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 @@ -45,6 +45,8 @@ import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; 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; @@ -54,7 +56,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests for {@link ContextLoader} and {@link ContextLoaderListener}. @@ -231,13 +232,9 @@ public class ContextLoaderTests { sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, StringUtils.arrayToCommaDelimitedString(new Object[] {UnknownContextInitializer.class.getName()})); ContextLoaderListener listener = new ContextLoaderListener(); - try { - listener.contextInitialized(new ServletContextEvent(sc)); - fail("expected exception"); - } - catch (ApplicationContextException ex) { - assertTrue(ex.getMessage().contains("not assignable")); - } + assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> + listener.contextInitialized(new ServletContextEvent(sc))) + .withMessageContaining("not assignable"); } @Test @@ -260,14 +257,9 @@ public class ContextLoaderTests { sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml"); ServletContextListener listener = new ContextLoaderListener(); ServletContextEvent event = new ServletContextEvent(sc); - try { - listener.contextInitialized(event); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - assertTrue(ex.getCause() instanceof FileNotFoundException); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + listener.contextInitialized(event)) + .withCauseInstanceOf(FileNotFoundException.class); } @Test @@ -277,14 +269,9 @@ public class ContextLoaderTests { "org.springframework.web.context.support.InvalidWebApplicationContext"); ServletContextListener listener = new ContextLoaderListener(); ServletContextEvent event = new ServletContextEvent(sc); - try { - listener.contextInitialized(event); - fail("Should have thrown ApplicationContextException"); - } - catch (ApplicationContextException ex) { - // expected - assertTrue(ex.getCause() instanceof ClassNotFoundException); - } + assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> + listener.contextInitialized(event)) + .withCauseInstanceOf(ClassNotFoundException.class); } @Test @@ -292,30 +279,20 @@ public class ContextLoaderTests { MockServletContext sc = new MockServletContext(""); ServletContextListener listener = new ContextLoaderListener(); ServletContextEvent event = new ServletContextEvent(sc); - try { - listener.contextInitialized(event); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - assertTrue(ex.getCause() instanceof IOException); - assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml")); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + listener.contextInitialized(event)) + .withCauseInstanceOf(IOException.class) + .satisfies(ex -> assertThat(ex.getCause()).hasMessageContaining("/WEB-INF/applicationContext.xml")); } @Test public void testFrameworkServletWithDefaultLocation() throws Exception { DispatcherServlet servlet = new DispatcherServlet(); servlet.setContextClass(XmlWebApplicationContext.class); - try { - servlet.init(new MockServletConfig(new MockServletContext(""), "test")); - fail("Should have thrown BeanDefinitionStoreException"); - } - catch (BeanDefinitionStoreException ex) { - // expected - assertTrue(ex.getCause() instanceof IOException); - assertTrue(ex.getCause().getMessage().contains("/WEB-INF/test-servlet.xml")); - } + assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> + servlet.init(new MockServletConfig(new MockServletContext(""), "test"))) + .withCauseInstanceOf(IOException.class) + .satisfies(ex -> assertThat(ex.getCause()).hasMessageContaining("/WEB-INF/test-servlet.xml")); } @Test @@ -347,25 +324,26 @@ public class ContextLoaderTests { assertTrue("Has kerry", context.containsBean("kerry")); } - @Test(expected = BeanCreationException.class) + @Test @SuppressWarnings("resource") public void testSingletonDestructionOnStartupFailure() throws IOException { - new ClassPathXmlApplicationContext(new String[] { - "/org/springframework/web/context/WEB-INF/applicationContext.xml", - "/org/springframework/web/context/WEB-INF/fail.xml" }) { + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext(new String[] { + "/org/springframework/web/context/WEB-INF/applicationContext.xml", + "/org/springframework/web/context/WEB-INF/fail.xml" }) { - @Override - public void refresh() throws BeansException { - try { - super.refresh(); - } - catch (BeanCreationException ex) { - DefaultListableBeanFactory factory = (DefaultListableBeanFactory) getBeanFactory(); - assertEquals(0, factory.getSingletonCount()); - throw ex; - } - } - }; + @Override + public void refresh() throws BeansException { + try { + super.refresh(); + } + catch (BeanCreationException ex) { + DefaultListableBeanFactory factory = (DefaultListableBeanFactory) getBeanFactory(); + assertEquals(0, factory.getSingletonCount()); + throw ex; + } + } + }); } 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 fd2865860ab..abc7ff38251 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 @@ -33,13 +33,15 @@ import org.springframework.context.NoSuchMessageException; import org.springframework.context.TestListener; import org.springframework.mock.web.test.MockServletContext; import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.Assert; 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; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -124,13 +126,8 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes wac.setNamespace("testNamespace"); wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"}); wac.refresh(); - try { - wac.getMessage("someMessage", null, Locale.getDefault()); - fail("Should have thrown NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // expected; - } + assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> + wac.getMessage("someMessage", null, Locale.getDefault())); String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault()); assertTrue("Default message returned", "default".equals(msg)); } @@ -180,34 +177,26 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes @Override public void afterPropertiesSet() { - if (this.initMethodInvoked) - fail(); + assertThat(this.initMethodInvoked).isFalse(); this.afterPropertiesSetInvoked = true; } /** Init method */ public void customInit() throws ServletException { - if (!this.afterPropertiesSetInvoked) - fail(); + assertThat(this.afterPropertiesSetInvoked).isTrue(); this.initMethodInvoked = true; } @Override public void destroy() { - if (this.customDestroyed) - fail(); - if (this.destroyed) { - throw new IllegalStateException("Already destroyed"); - } + assertThat(this.customDestroyed).isFalse(); + Assert.state(!this.destroyed, "Already destroyed"); this.destroyed = true; } public void customDestroy() { - if (!this.destroyed) - fail(); - if (this.customDestroyed) { - throw new IllegalStateException("Already customDestroyed"); - } + assertThat(this.destroyed).isTrue(); + Assert.state(!this.customDestroyed, "Already customDestroyed"); this.customDestroyed = true; } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java index fa9c6b59307..2d90ce75cd6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java @@ -31,9 +31,10 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.HttpRequestHandler; import org.springframework.web.context.WebApplicationContext; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -74,23 +75,15 @@ public class HttpRequestHandlerTests { servlet.service(request, response); assertEquals("myResponse", response.getContentAsString()); - try { - request.setParameter("exception", "ServletException"); - servlet.service(request, response); - fail("Should have thrown ServletException"); - } - catch (ServletException ex) { - assertEquals("test", ex.getMessage()); - } + request.setParameter("exception", "ServletException"); + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> + servlet.service(request, response)) + .withMessage("test"); - try { - request.setParameter("exception", "IOException"); - servlet.service(request, response); - fail("Should have thrown IOException"); - } - catch (IOException ex) { - assertEquals("test", ex.getMessage()); - } + request.setParameter("exception", "IOException"); + assertThatIOException().isThrownBy(() -> + servlet.service(request, response)) + .withMessage("test"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java index 8345e48290e..a8fbe156aef 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java @@ -31,10 +31,10 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockServletContext; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests for various ServletContext-related support classes. @@ -73,15 +73,10 @@ public class ServletContextSupportTests { pvs.add("attributeName", "myAttr"); wac.registerSingleton("importedAttr", ServletContextAttributeFactoryBean.class, pvs); - try { - wac.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.getCause() instanceof IllegalStateException); - assertTrue(ex.getCause().getMessage().contains("myAttr")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + wac::refresh) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("myAttr"); } @Test @@ -112,15 +107,10 @@ public class ServletContextSupportTests { pvs.add("initParamName", "myParam"); wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs); - try { - wac.refresh(); - fail("Should have thrown BeanCreationException"); - } - catch (BeanCreationException ex) { - // expected - assertTrue(ex.getCause() instanceof IllegalStateException); - assertTrue(ex.getCause().getMessage().contains("myParam")); - } + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + wac::refresh) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("myParam"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java index f0c7a1e8a98..b905553857b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java @@ -25,8 +25,8 @@ import org.springframework.context.support.StaticApplicationContext; import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -55,13 +55,8 @@ public class WebApplicationObjectSupportTests { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class)); WebApplicationObjectSupport wao = (WebApplicationObjectSupport) ac.getBean("test"); - try { - wao.getWebApplicationContext(); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy( + wao::getWebApplicationContext); } 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 a06a370372e..81869f46b9e 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,6 +58,8 @@ 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.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; @@ -70,7 +72,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -295,14 +296,9 @@ public class DispatcherServletTests { request.addUserRole("role1"); request.addParameter("fail", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); - try { - complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl())); - } - catch (ServletException ex) { - fail("Should not have thrown ServletException: " + ex.getMessage()); - } + complexDispatcherServlet.service(request, response); + assertEquals(200, response.getStatus()); + assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl())); } @Test @@ -416,13 +412,8 @@ public class DispatcherServletTests { request.addParameter("theme", "mytheme"); request.addParameter("theme2", "theme"); MockHttpServletResponse response = new MockHttpServletResponse(); - try { - complexDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); - } - catch (ServletException ex) { - fail("Should not have thrown ServletException: " + ex.getMessage()); - } + complexDispatcherServlet.service(request, response); + assertTrue("Not forwarded", response.getForwardedUrl() == null); } @Test @@ -430,13 +421,8 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do"); request.addPreferredLocale(Locale.CANADA); MockHttpServletResponse response = new MockHttpServletResponse(); - try { - complexDispatcherServlet.service(request, response); - assertTrue("Correct response", response.getStatus() == HttpServletResponse.SC_FORBIDDEN); - } - catch (ServletException ex) { - fail("Should not have thrown ServletException: " + ex.getMessage()); - } + complexDispatcherServlet.service(request, response); + assertTrue("Correct response", response.getStatus() == HttpServletResponse.SC_FORBIDDEN); } @Test @@ -572,14 +558,9 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do"); MockHttpServletResponse response = new MockHttpServletResponse(); - try { - complexDispatcherServlet.service(request, response); - fail("Should have thrown ServletException"); - } - catch (ServletException ex) { - // expected - assertTrue(ex.getMessage().contains("No adapter for handler")); - } + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> + complexDispatcherServlet.service(request, response)) + .withMessageContaining("No adapter for handler"); } @Test @@ -592,14 +573,9 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do"); MockHttpServletResponse response = new MockHttpServletResponse(); - try { - complexDispatcherServlet.service(request, response); - fail("Should have thrown ServletException"); - } - catch (ServletException ex) { - // expected - assertTrue(ex.getMessage().contains("failed0")); - } + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> + complexDispatcherServlet.service(request, response)) + .withMessageContaining("failed0"); } @Test @@ -733,13 +709,8 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview"); MockHttpServletResponse response = new MockHttpServletResponse(); - try { - complexDispatcherServlet.service(request, response); - fail("Should have thrown ServletException"); - } - catch (ServletException ex) { - ex.printStackTrace(); - } + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> + complexDispatcherServlet.service(request, response)); } @Test @@ -812,12 +783,8 @@ public class DispatcherServletTests { ConfigurableEnvironment env1 = new StandardServletEnvironment(); servlet.setEnvironment(env1); // should succeed assertThat(servlet.getEnvironment(), sameInstance(env1)); - try { - servlet.setEnvironment(new DummyEnvironment()); - fail("expected IllegalArgumentException for non-configurable Environment"); - } - catch (IllegalArgumentException ex) { - } + assertThatIllegalArgumentException().as("non-configurable Environment").isThrownBy(() -> + servlet.setEnvironment(new DummyEnvironment())); class CustomServletEnvironment extends StandardServletEnvironment { } @SuppressWarnings("serial") DispatcherServlet custom = new DispatcherServlet() { 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 ca93832bff9..bde52718430 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 @@ -141,6 +141,7 @@ 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.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.instanceOf; @@ -262,7 +263,7 @@ public class MvcNamespaceTests { assertEquals(BeanNameUrlHandlerMapping.class, introspector.getHandlerMappings().get(1).getClass()); } - @Test(expected = TypeMismatchException.class) + @Test public void testCustomConversionService() throws Exception { loadBeanDefinitions("mvc-config-custom-conversion-service.xml"); @@ -285,7 +286,8 @@ public class MvcNamespaceTests { RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); assertNotNull(adapter); - adapter.handle(request, response, handlerMethod); + assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> + adapter.handle(request, response, handlerMethod)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java index c1b39a5857c..bd2fb48488e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java @@ -44,6 +44,8 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.HttpMediaTypeNotSupportedException; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; /** @@ -150,7 +152,7 @@ public class DefaultServerRequestTests { assertEquals("bar", request.pathVariable("foo")); } - @Test(expected = IllegalArgumentException.class) + @Test public void pathVariableNotFound() { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/"); Map pathVariables = Collections.singletonMap("foo", "bar"); @@ -160,7 +162,8 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - request.pathVariable("baz"); + assertThatIllegalArgumentException().isThrownBy(() -> + request.pathVariable("baz")); } @Test @@ -253,7 +256,7 @@ public class DefaultServerRequestTests { assertEquals("bar", result.get(1)); } - @Test(expected = HttpMediaTypeNotSupportedException.class) + @Test public void bodyUnacceptable() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/"); servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE); @@ -262,7 +265,8 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); - request.body(String.class); + assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() -> + request.body(String.class)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java index 9b1aaa871fc..d70dc0170f3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java @@ -31,7 +31,6 @@ import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.web.servlet.function.RequestPredicates.HEAD; /** @@ -95,9 +94,8 @@ public class RouterFunctionBuilderTests { try { return handlerFunction.handle(request); } - catch (Exception e) { - fail(e.getMessage()); - return null; + catch (Exception ex) { + throw new AssertionError(ex.getMessage(), ex); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java index 48181574a07..5d94ec1812f 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java @@ -26,7 +26,6 @@ import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Arjen Poutsma @@ -112,9 +111,8 @@ public class RouterFunctionTests { try { return hf.handle(request); } - catch (Exception e) { - fail(e.getMessage()); - return null; + catch (Exception ex) { + throw new AssertionError(ex.getMessage(), ex); } }); assertTrue(resultHandlerFunction.isPresent()); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java index 9cbf2d20e26..a5d2db4ff74 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java @@ -29,8 +29,8 @@ import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -193,13 +193,8 @@ public class BeanNameUrlHandlerMappingTests { @Test public void doubleMappings() throws ServletException { BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping"); - try { - hm.registerHandler("/mypath/welcome.html", new Object()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + assertThatIllegalStateException().isThrownBy(() -> + hm.registerHandler("/mypath/welcome.html", new Object())); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java index f5486e5f4c9..187fbbc8b99 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java @@ -39,6 +39,7 @@ import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -109,14 +110,15 @@ public class HandlerMappingIntrospectorTests { assertNull("Attributes changes not ignored", request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE)); } - @Test(expected = IllegalStateException.class) + @Test public void getMatchableWhereHandlerMappingDoesNotImplementMatchableInterface() throws Exception { StaticWebApplicationContext cxt = new StaticWebApplicationContext(); cxt.registerSingleton("hm1", TestHandlerMapping.class); cxt.refresh(); MockHttpServletRequest request = new MockHttpServletRequest(); - getIntrospector(cxt).getMatchableHandlerMapping(request); + assertThatIllegalStateException().isThrownBy(() -> + getIntrospector(cxt).getMatchableHandlerMapping(request)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java index 733c47b9145..da989b72c54 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java @@ -38,6 +38,7 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.util.UrlPathHelper; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -70,10 +71,11 @@ public class HandlerMethodMappingTests { } - @Test(expected = IllegalStateException.class) + @Test public void registerDuplicates() { this.mapping.registerMapping("foo", this.handler, this.method1); - this.mapping.registerMapping("foo", this.handler, this.method2); + assertThatIllegalStateException().isThrownBy(() -> + this.mapping.registerMapping("foo", this.handler, this.method2)); } @Test @@ -98,12 +100,13 @@ public class HandlerMethodMappingTests { assertEquals(result, request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); } - @Test(expected = IllegalStateException.class) + @Test public void ambiguousMatch() throws Exception { this.mapping.registerMapping("/f?o", this.handler, this.method1); this.mapping.registerMapping("/fo?", this.handler, this.method2); - this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", "/foo")); + assertThatIllegalStateException().isThrownBy(() -> + this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", "/foo"))); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java index beb9ac05de7..b987f84b6d5 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java @@ -32,11 +32,12 @@ import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rod Johnson @@ -57,14 +58,10 @@ public class SimpleUrlHandlerMappingTests { wac.setServletContext(sc); wac.setNamespace("map2err"); wac.setConfigLocations("/org/springframework/web/servlet/handler/map2err.xml"); - try { - wac.refresh(); - fail("Should have thrown NoSuchBeanDefinitionException"); - } - catch (FatalBeanException ex) { - NoSuchBeanDefinitionException nestedEx = (NoSuchBeanDefinitionException) ex.getCause(); - assertEquals("mainControlle", nestedEx.getBeanName()); - } + assertThatExceptionOfType(FatalBeanException.class).isThrownBy( + wac::refresh) + .withCauseInstanceOf(NoSuchBeanDefinitionException.class) + .satisfies(ex -> assertThat(((NoSuchBeanDefinitionException) ex.getCause()).getBeanName()).isEqualTo("mainControlle")); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java index 98945f0e646..fe52f1a50d3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java @@ -31,12 +31,12 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Alef Arendsen @@ -93,14 +93,10 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setCookieName("LanguageKoekje"); - try { - resolver.resolveLocaleContext(request); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("LanguageKoekje")); - assertTrue(ex.getMessage().contains("++ GMT+1")); - } + assertThatIllegalStateException().isThrownBy(() -> + resolver.resolveLocaleContext(request)) + .withMessageContaining("LanguageKoekje") + .withMessageContaining("++ GMT+1"); } @Test @@ -128,14 +124,10 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setCookieName("LanguageKoekje"); - try { - resolver.resolveLocaleContext(request); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("LanguageKoekje")); - assertTrue(ex.getMessage().contains("nl X-MT")); - } + assertThatIllegalStateException().isThrownBy(() -> + resolver.resolveLocaleContext(request)) + .withMessageContaining("LanguageKoekje") + .withMessageContaining("nl X-MT"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java index 9394348925f..b11da726934 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java @@ -31,6 +31,7 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.servlet.LocaleContextResolver; import org.springframework.web.servlet.LocaleResolver; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -75,16 +76,13 @@ public class LocaleResolverTests { // set new locale try { localeResolver.setLocale(request, response, Locale.GERMANY); - if (!shouldSet) - fail("should not be able to set Locale"); + assertThat(shouldSet).as("should not be able to set Locale").isTrue(); // check new locale locale = localeResolver.resolveLocale(request); assertEquals(Locale.GERMANY, locale); } catch (UnsupportedOperationException ex) { - if (shouldSet) { - fail("should be able to set Locale"); - } + assertThat(shouldSet).as("should be able to set Locale").isFalse(); } // check LocaleContext 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 12c8bcdc28d..c9e74cb2bee 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 @@ -24,6 +24,7 @@ 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.assertThatIllegalArgumentException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -160,10 +161,11 @@ public class WebContentInterceptorTests { assertThat(cacheControlHeaders, Matchers.contains("max-age=10, must-revalidate")); } - @Test(expected = IllegalArgumentException.class) + @Test public void throwsExceptionWithNullPathMatcher() throws Exception { WebContentInterceptor interceptor = new WebContentInterceptor(); - interceptor.setPathMatcher(null); + assertThatIllegalArgumentException().isThrownBy(() -> + interceptor.setPathMatcher(null)); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java index ee7b9f0e3d0..2dcb44940f9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java @@ -24,6 +24,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -73,11 +74,12 @@ public class CompositeRequestConditionTests { assertSame(notEmpty, empty.combine(notEmpty)); } - @Test(expected = IllegalArgumentException.class) + @Test public void combineDifferentLength() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1); - cond1.combine(cond2); + assertThatIllegalArgumentException().isThrownBy(() -> + cond1.combine(cond2)); } @Test @@ -132,11 +134,12 @@ public class CompositeRequestConditionTests { assertEquals(1, empty.compareTo(notEmpty, request)); } - @Test(expected = IllegalArgumentException.class) + @Test public void compareDifferentLength() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1); - cond1.compareTo(cond2, new MockHttpServletRequest()); + assertThatIllegalArgumentException().isThrownBy(() -> + cond1.compareTo(cond2, new MockHttpServletRequest())); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java index 84ce92d6287..f0fb3445b1c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java @@ -25,11 +25,11 @@ import org.springframework.http.HttpHeaders; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Arjen Poutsma @@ -207,21 +207,8 @@ public class ConsumesRequestConditionTests { private void assertConditions(ConsumesRequestCondition condition, String... expected) { Collection expressions = condition.getContent(); - assertEquals("Invalid amount of conditions", expressions.size(), expected.length); - for (String s : expected) { - boolean found = false; - for (ConsumeMediaTypeExpression expr : expressions) { - String conditionMediaType = expr.getMediaType().toString(); - if (conditionMediaType.equals(s)) { - found = true; - break; - - } - } - if (!found) { - fail("Condition [" + s + "] not found"); - } - } + assertThat(expressions.stream().map(expr -> expr.getMediaType().toString())) + .containsExactlyInAnyOrder(expected); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java index bcac6cdbb25..805e46cfdc3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java @@ -30,11 +30,11 @@ import org.springframework.web.accept.FixedContentNegotiationStrategy; import org.springframework.web.accept.HeaderContentNegotiationStrategy; import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.ProduceMediaTypeExpression; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Unit tests for {@link ProducesRequestCondition}. @@ -370,21 +370,8 @@ public class ProducesRequestConditionTests { private void assertConditions(ProducesRequestCondition condition, String... expected) { Collection expressions = condition.getContent(); - assertEquals("Invalid number of conditions", expressions.size(), expected.length); - for (String s : expected) { - boolean found = false; - for (ProduceMediaTypeExpression expr : expressions) { - String conditionMediaType = expr.getMediaType().toString(); - if (conditionMediaType.equals(s)) { - found = true; - break; - - } - } - if (!found) { - fail("Condition [" + s + "] not found"); - } - } + assertThat(expressions.stream().map(expr -> expr.getMediaType().toString())) + .containsExactlyInAnyOrder(expected); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java index 0feb9a18f54..567d3c95ed1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -53,11 +54,12 @@ public class RequestConditionHolderTests { assertSame(notEmpty, empty.combine(notEmpty)); } - @Test(expected = ClassCastException.class) + @Test public void combineIncompatible() { RequestConditionHolder params = new RequestConditionHolder(new ParamsRequestCondition("name")); RequestConditionHolder headers = new RequestConditionHolder(new HeadersRequestCondition("name")); - params.combine(headers); + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + params.combine(headers)); } @Test @@ -112,11 +114,12 @@ public class RequestConditionHolderTests { assertEquals(1, empty.compareTo(notEmpty, request)); } - @Test(expected = ClassCastException.class) + @Test public void compareIncompatible() { RequestConditionHolder params = new RequestConditionHolder(new ParamsRequestCondition("name")); RequestConditionHolder headers = new RequestConditionHolder(new HeadersRequestCondition("name")); - params.compareTo(headers, new MockHttpServletRequest()); + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> + params.compareTo(headers, new MockHttpServletRequest())); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index e04a7c01aa1..a7a3ec892b7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -20,7 +20,6 @@ import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; @@ -59,14 +58,12 @@ import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition; import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; import org.springframework.web.util.UrlPathHelper; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * Test fixture with {@link RequestMappingInfoHandlerMapping}. @@ -150,23 +147,19 @@ public class RequestMappingInfoHandlerMappingTests { @Test public void getHandlerRequestMethodNotAllowed() throws Exception { - try { - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar"); - this.handlerMapping.getHandler(request); - fail("HttpRequestMethodNotSupportedException expected"); - } - catch (HttpRequestMethodNotSupportedException ex) { - assertArrayEquals("Invalid supported methods", new String[]{"GET", "HEAD"}, - ex.getSupportedMethods()); - } + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar"); + assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() -> + this.handlerMapping.getHandler(request)) + .satisfies(ex -> assertThat(ex.getSupportedMethods()).containsExactly("GET", "HEAD")); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-9603 + @Test // SPR-9603 public void getHandlerRequestMethodMatchFalsePositive() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/users"); request.addHeader("Accept", "application/xml"); this.handlerMapping.registerHandler(new UserController()); - this.handlerMapping.getHandler(request); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + this.handlerMapping.getHandler(request)); } @Test // SPR-8462 @@ -186,15 +179,11 @@ public class RequestMappingInfoHandlerMappingTests { @Test public void getHandlerTestInvalidContentType() throws Exception { - try { - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1"); - request.setContentType("bogus"); - this.handlerMapping.getHandler(request); - fail("HttpMediaTypeNotSupportedException expected"); - } - catch (HttpMediaTypeNotSupportedException ex) { - assertEquals("Invalid mime type \"bogus\": does not contain '/'", ex.getMessage()); - } + MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1"); + request.setContentType("bogus"); + assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() -> + this.handlerMapping.getHandler(request)) + .withMessage("Invalid mime type \"bogus\": does not contain '/'"); } @Test // SPR-8462 @@ -206,17 +195,11 @@ public class RequestMappingInfoHandlerMappingTests { @Test // SPR-12854 public void getHandlerUnsatisfiedServletRequestParameterException() throws Exception { - try { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params"); - this.handlerMapping.getHandler(request); - fail("UnsatisfiedServletRequestParameterException expected"); - } - catch (UnsatisfiedServletRequestParameterException ex) { - List groups = ex.getParamConditionGroups(); - assertEquals(2, groups.size()); - assertThat(Arrays.asList("foo=bar", "bar=baz"), - containsInAnyOrder(groups.get(0)[0], groups.get(1)[0])); - } + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params"); + assertThatExceptionOfType(UnsatisfiedServletRequestParameterException.class).isThrownBy(() -> + this.handlerMapping.getHandler(request)) + .satisfies(ex -> assertThat(ex.getParamConditionGroups().stream().map(group -> group[0])) + .containsExactlyInAnyOrder("foo=bar", "bar=baz")); } @Test @@ -395,17 +378,11 @@ public class RequestMappingInfoHandlerMappingTests { } private void testHttpMediaTypeNotSupportedException(String url) throws Exception { - try { - MockHttpServletRequest request = new MockHttpServletRequest("PUT", url); - request.setContentType("application/json"); - this.handlerMapping.getHandler(request); - fail("HttpMediaTypeNotSupportedException expected"); - } - catch (HttpMediaTypeNotSupportedException ex) { - assertEquals("Invalid supported consumable media types", - Collections.singletonList(new MediaType("application", "xml")), - ex.getSupportedMediaTypes()); - } + MockHttpServletRequest request = new MockHttpServletRequest("PUT", url); + request.setContentType("application/json"); + assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() -> + this.handlerMapping.getHandler(request)) + .satisfies(ex -> assertThat(ex.getSupportedMediaTypes()).containsExactly(MediaType.APPLICATION_XML)); } private void testHttpOptions(String requestURI, String allowHeader) throws Exception { @@ -422,17 +399,11 @@ public class RequestMappingInfoHandlerMappingTests { } private void testHttpMediaTypeNotAcceptableException(String url) throws Exception { - try { - MockHttpServletRequest request = new MockHttpServletRequest("GET", url); - request.addHeader("Accept", "application/json"); - this.handlerMapping.getHandler(request); - fail("HttpMediaTypeNotAcceptableException expected"); - } - catch (HttpMediaTypeNotAcceptableException ex) { - assertEquals("Invalid supported producible media types", - Collections.singletonList(new MediaType("application", "xml")), - ex.getSupportedMediaTypes()); - } + MockHttpServletRequest request = new MockHttpServletRequest("GET", url); + request.addHeader("Accept", "application/json"); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + this.handlerMapping.getHandler(request)) + .satisfies(ex -> assertThat(ex.getSupportedMediaTypes()).containsExactly(MediaType.APPLICATION_XML)); } private void handleMatch(MockHttpServletRequest request, String pattern, String lookupPath) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java index c86b3f8d856..6ab478484ae 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java @@ -41,13 +41,13 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -96,13 +96,9 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { @Test public void resolve() throws Exception { MethodParameter param = initMethodParameter(0); - try { - testResolveArgument(param); - fail("Should be required by default"); - } - catch (ServletRequestBindingException ex) { - assertTrue(ex.getMessage().startsWith("Missing ")); - } + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + testResolveArgument(param)) + .withMessageStartingWith("Missing "); Foo foo = new Foo(); this.webRequest.setAttribute("foo", foo, getScope()); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java index 7a8bc69ab64..5d42eed7324 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java @@ -36,6 +36,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -109,19 +110,21 @@ public class MatrixVariablesMethodArgumentResolverTests { assertEquals("2013", resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); } - @Test(expected = ServletRequestBindingException.class) + @Test public void resolveArgumentMultipleMatches() throws Exception { getVariablesFor("var1").add("colors", "red"); getVariablesFor("var2").add("colors", "green"); MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); - this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); } - @Test(expected = ServletRequestBindingException.class) + @Test public void resolveArgumentRequired() throws Exception { MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); - this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); + assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> + this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java index 38d7ded4e02..63785903e94 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java @@ -33,6 +33,7 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -77,11 +78,12 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests { assertFalse(mavContainer.isRequestHandled()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void modelAndViewResolverUnresolved() throws Exception { MethodParameter returnType = new MethodParameter(getClass().getDeclaredMethod("intReturnValue"), -1); mavResolvers.add(new TestModelAndViewResolver(TestBean.class)); - handler.handleReturnValue(99, returnType, mavContainer, request); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + handler.handleReturnValue(99, returnType, mavContainer, request)); } @Test @@ -94,10 +96,11 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests { assertTrue(mavContainer.getModel().isEmpty()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void handleSimpleType() throws Exception { MethodParameter returnType = new MethodParameter(getClass().getDeclaredMethod("intReturnValue"), -1); - handler.handleReturnValue(55, returnType, mavContainer, request); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> + handler.handleReturnValue(55, returnType, mavContainer, request)); } @Test 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 1b4fb22cbd6..b3a58e1b114 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 @@ -62,6 +62,7 @@ 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.assertThatIllegalStateException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -383,12 +384,13 @@ public class MvcUriComponentsBuilderTests { assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString()); } - @Test(expected = IllegalStateException.class) // SPR-16710 + @Test // SPR-16710 public void fromMethodCallWithStringReturnType() { - UriComponents uriComponents = fromMethodCall( - on(BookingControllerWithString.class).getBooking(21L)).buildAndExpand(42); - - assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString()); + assertThatIllegalStateException().isThrownBy(() -> { + UriComponents uriComponents = fromMethodCall( + on(BookingControllerWithString.class).getBooking(21L)).buildAndExpand(42); + uriComponents.encode().toUri().toString(); + }); } @Test // SPR-16710 diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java index cf1b8ceb42e..00f1ccde423 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java @@ -40,12 +40,12 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.View; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test fixture with {@link PathVariableMethodArgumentResolver}. @@ -164,10 +164,10 @@ public class PathVariableMethodArgumentResolverTests { assertEquals("oldValue", pathVars.get("oldName")); } - @Test(expected = MissingPathVariableException.class) + @Test public void handleMissingValue() throws Exception { - resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null); - fail("Unresolved path variable should lead to exception"); + assertThatExceptionOfType(MissingPathVariableException.class).isThrownBy(() -> + resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java index 1378751da43..5551e750819 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java @@ -42,6 +42,7 @@ import org.springframework.mock.web.test.MockMultipartFile; import org.springframework.mock.web.test.MockMultipartHttpServletRequest; import org.springframework.mock.web.test.MockPart; import org.springframework.util.ReflectionUtils; +import org.springframework.validation.BindingResult; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.WebDataBinder; @@ -55,12 +56,13 @@ import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.MissingServletRequestPartException; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -280,15 +282,14 @@ public class RequestPartMethodArgumentResolverTests { @Test public void resolveRequestPartNotValid() throws Exception { - try { - testResolveArgument(new SimpleBean(null), paramValidRequestPart); - fail("Expected exception"); - } - catch (MethodArgumentNotValidException ex) { - assertEquals("requestPart", ex.getBindingResult().getObjectName()); - assertEquals(1, ex.getBindingResult().getErrorCount()); - assertNotNull(ex.getBindingResult().getFieldError("name")); - } + assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() -> + testResolveArgument(new SimpleBean(null), paramValidRequestPart)) + .satisfies(ex -> { + BindingResult bindingResult = ex.getBindingResult(); + assertThat(bindingResult.getObjectName()).isEqualTo("requestPart"); + assertThat(bindingResult.getErrorCount()).isEqualTo(1); + assertThat(bindingResult.getFieldError("name")).isNotNull(); + }); } @Test @@ -298,13 +299,9 @@ public class RequestPartMethodArgumentResolverTests { @Test public void resolveRequestPartRequired() throws Exception { - try { - testResolveArgument(null, paramValidRequestPart); - fail("Expected exception"); - } - catch (MissingServletRequestPartException ex) { - assertEquals("requestPart", ex.getRequestPartName()); - } + assertThatExceptionOfType(MissingServletRequestPartException.class).isThrownBy(() -> + testResolveArgument(null, paramValidRequestPart)) + .satisfies(ex -> assertThat(ex.getRequestPartName()).isEqualTo("requestPart")); } @Test @@ -312,10 +309,11 @@ public class RequestPartMethodArgumentResolverTests { testResolveArgument(new SimpleBean("foo"), paramValidRequestPart); } - @Test(expected = MultipartException.class) + @Test public void isMultipartRequest() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); - resolver.resolveArgument(paramMultipartFile, new ModelAndViewContainer(), new ServletWebRequest(request), null); + assertThatExceptionOfType(MultipartException.class).isThrownBy(() -> + resolver.resolveArgument(paramMultipartFile, new ModelAndViewContainer(), new ServletWebRequest(request), null)); } @Test // SPR-9079 diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java index 7b37bf3ba48..f21cc73584d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java @@ -40,6 +40,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.lang.Nullable; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import org.springframework.validation.BindingResult; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; @@ -53,12 +54,12 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.argThat; @@ -173,15 +174,14 @@ public class RequestResponseBodyMethodProcessorMockTests { @Test public void resolveArgumentNotValid() throws Exception { - try { - testResolveArgumentWithValidation(new SimpleBean(null)); - fail("Expected exception"); - } - catch (MethodArgumentNotValidException e) { - assertEquals("simpleBean", e.getBindingResult().getObjectName()); - assertEquals(1, e.getBindingResult().getErrorCount()); - assertNotNull(e.getBindingResult().getFieldError("name")); - } + assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() -> + testResolveArgumentWithValidation(new SimpleBean(null))) + .satisfies(ex -> { + BindingResult bindingResult = ex.getBindingResult(); + assertThat(bindingResult.getObjectName()).isEqualTo("simpleBean"); + assertThat(bindingResult.getErrorCount()).isEqualTo(1); + assertThat(bindingResult.getFieldError("name")).isNotNull(); + }); } @Test @@ -204,7 +204,7 @@ public class RequestResponseBodyMethodProcessorMockTests { processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory()); } - @Test(expected = HttpMediaTypeNotSupportedException.class) + @Test public void resolveArgumentCannotRead() throws Exception { MediaType contentType = MediaType.TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); @@ -212,31 +212,35 @@ public class RequestResponseBodyMethodProcessorMockTests { given(stringMessageConverter.canRead(String.class, contentType)).willReturn(false); - processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() -> + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null)); } - @Test(expected = HttpMediaTypeNotSupportedException.class) + @Test public void resolveArgumentNoContentType() throws Exception { servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8)); given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); - processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() -> + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null)); } - @Test(expected = HttpMediaTypeNotSupportedException.class) + @Test public void resolveArgumentInvalidContentType() throws Exception { this.servletRequest.setContentType("bad"); servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8)); - processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() -> + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null)); } - @Test(expected = HttpMessageNotReadableException.class) // SPR-9942 + @Test // SPR-9942 public void resolveArgumentRequiredNoContent() throws Exception { servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE); servletRequest.setContent(new byte[0]); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(null); - assertNull(processor.resolveArgument(paramRequestBodyString, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + processor.resolveArgument(paramRequestBodyString, mavContainer, + webRequest, new ValidatingBinderFactory())); } @Test @@ -336,7 +340,7 @@ public class RequestResponseBodyMethodProcessorMockTests { } - @Test(expected = HttpMediaTypeNotAcceptableException.class) + @Test public void handleReturnValueNotAcceptable() throws Exception { MediaType accepted = MediaType.APPLICATION_ATOM_XML; servletRequest.addHeader("Accept", accepted.toString()); @@ -345,10 +349,11 @@ public class RequestResponseBodyMethodProcessorMockTests { given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false); - processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest)); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) + @Test public void handleReturnValueNotAcceptableProduces() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); @@ -357,7 +362,8 @@ public class RequestResponseBodyMethodProcessorMockTests { given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false); - processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); + assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> + processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java index a5eb5573a98..a8ded42cbca 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java @@ -70,6 +70,8 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -196,14 +198,15 @@ public class RequestResponseBodyMethodProcessorTests { assertEquals("foobarbaz", result); } - @Test(expected = HttpMessageNotReadableException.class) // SPR-9942 + @Test // SPR-9942 public void resolveArgumentRequiredNoContent() throws Exception { this.servletRequest.setContent(new byte[0]); this.servletRequest.setContentType("text/plain"); List> converters = new ArrayList<>(); converters.add(new StringHttpMessageConverter()); RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); - processor.resolveArgument(paramString, container, request, factory); + assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> + processor.resolveArgument(paramString, container, request, factory)); } @Test // SPR-12778 @@ -361,12 +364,14 @@ public class RequestResponseBodyMethodProcessorTests { // SPR-13135 - @Test(expected = IllegalArgumentException.class) + @Test public void handleReturnValueWithInvalidReturnType() throws Exception { Method method = getClass().getDeclaredMethod("handleAndReturnOutputStream"); MethodParameter returnType = new MethodParameter(method, -1); - RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(new ArrayList<>()); - processor.writeWithMessageConverters(new ByteArrayOutputStream(), returnType, this.request); + assertThatIllegalArgumentException().isThrownBy(() -> { + RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(new ArrayList<>()); + processor.writeWithMessageConverters(new ByteArrayOutputStream(), returnType, this.request); + }); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java index 6b878aeac73..7c348b3437d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java @@ -26,8 +26,9 @@ import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; +import static org.assertj.core.api.Assertions.assertThatIOException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -98,10 +99,11 @@ public class ResponseBodyEmitterTests { verifyNoMoreInteractions(this.handler); } - @Test(expected = IllegalStateException.class) + @Test public void sendFailsAfterComplete() throws Exception { this.emitter.complete(); - this.emitter.send("foo"); + assertThatIllegalStateException().isThrownBy(() -> + this.emitter.send("foo")); } @Test @@ -151,13 +153,8 @@ public class ResponseBodyEmitterTests { IOException failure = new IOException(); willThrow(failure).given(this.handler).send("foo", MediaType.TEXT_PLAIN); - try { - this.emitter.send("foo", MediaType.TEXT_PLAIN); - fail("Expected exception"); - } - catch (IOException ex) { - // expected - } + assertThatIOException().isThrownBy(() -> + this.emitter.send("foo", MediaType.TEXT_PLAIN)); verify(this.handler).send("foo", MediaType.TEXT_PLAIN); verifyNoMoreInteractions(this.handler); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java index 05bb531e442..6d1f199a200 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java @@ -52,10 +52,10 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandlerCom import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.view.RedirectView; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test fixture with {@link ServletInvocableHandlerMethod}. @@ -148,13 +148,13 @@ public class ServletInvocableHandlerMethodTests { assertEquals("400 Bad Request", this.response.getErrorMessage()); } - @Test(expected = HttpMessageNotWritableException.class) + @Test public void invokeAndHandle_Exception() throws Exception { this.returnValueHandlers.addHandler(new ExceptionRaisingReturnValueHandler()); ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "handle"); - handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - fail("Expected exception"); + assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> + handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java index 8637c442af8..4e780f4b9bb 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java @@ -19,6 +19,7 @@ package org.springframework.web.servlet.resource; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -44,9 +45,10 @@ public class FixedVersionStrategyTests { } - @Test(expected = IllegalArgumentException.class) + @Test public void emptyPrefixVersion() { - new FixedVersionStrategy(" "); + assertThatIllegalArgumentException().isThrownBy(() -> + new FixedVersionStrategy(" ")); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java index 7d70d21a5de..e55067fbc81 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 @@ -42,6 +42,8 @@ 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.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; @@ -510,16 +512,18 @@ public class ResourceHttpRequestHandlerTests { assertEquals(404, this.response.getStatus()); } - @Test(expected = IllegalStateException.class) + @Test public void noPathWithinHandlerMappingAttribute() throws Exception { - this.handler.handleRequest(this.request, this.response); + assertThatIllegalStateException().isThrownBy(() -> + this.handler.handleRequest(this.request, this.response)); } - @Test(expected = HttpRequestMethodNotSupportedException.class) + @Test public void unsupportedHttpMethod() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.request.setMethod("POST"); - this.handler.handleRequest(this.request, this.response); + assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() -> + this.handler.handleRequest(this.request, this.response)); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java index ac8ffdb576c..5dd4f270765 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java @@ -41,12 +41,12 @@ import org.springframework.web.servlet.support.BindStatus; import org.springframework.web.servlet.tags.form.FormTag; import org.springframework.web.servlet.tags.form.TagWriter; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Juergen Hoeller @@ -629,13 +629,8 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - try { - tag.doStartTag(); - fail("Should have thrown JspException"); - } - catch (JspException ex) { - // expected - } + assertThatExceptionOfType(JspException.class).isThrownBy( + tag::doStartTag); } @@ -906,13 +901,8 @@ public class BindTagTests extends AbstractTagTests { transform.setPageContext(pc); transform.setVar("var"); transform.setValue("bla"); - try { - transform.doStartTag(); - fail("Tag can be executed outside BindTag"); - } - catch (JspException e) { - // this is ok! - } + assertThatExceptionOfType(JspException.class).as("executed outside BindTag").isThrownBy( + transform::doStartTag); // now try to execute the tag outside a bindtag, but inside a messageTag MessageTag message = new MessageTag(); @@ -922,13 +912,8 @@ public class BindTagTests extends AbstractTagTests { transform.setVar("var"); transform.setValue("bla"); transform.setParent(message); - try { - transform.doStartTag(); - fail("Tag can be executed outside BindTag and inside messagetag"); - } - catch (JspException e) { - // this is ok! - } + assertThatExceptionOfType(JspException.class).as("executed outside BindTag and inside messagetag").isThrownBy( + transform::doStartTag); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java index ffd04a1e355..e0aae341ff8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockBodyContent; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -122,12 +123,13 @@ public class ParamTagTests extends AbstractTagTests { assertEquals("value2", parent.getParam().getValue()); } - @Test(expected = JspException.class) + @Test public void paramWithNoParent() throws Exception { tag.setName("name"); tag.setValue("value"); tag.setParent(null); - tag.doEndTag(); + assertThatExceptionOfType(JspException.class).isThrownBy( + tag::doEndTag); } @SuppressWarnings("serial") diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java index e454aa55cd0..d5ddd16c472 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java @@ -39,9 +39,9 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -613,14 +613,9 @@ public class CheckboxTagTests extends AbstractFormTagTests { @Test public void withNullValue() throws Exception { - try { - this.tag.setPath("name"); - this.tag.doStartTag(); - fail("Should not be able to render with a null value when binding to a non-boolean."); - } - catch (IllegalArgumentException e) { - // success - } + this.tag.setPath("name"); + assertThatIllegalArgumentException().as("null value binding to a non-boolean").isThrownBy( + this.tag::doStartTag); } @Test @@ -648,13 +643,9 @@ public class CheckboxTagTests extends AbstractFormTagTests { @Test public void dynamicTypeAttribute() throws JspException { - try { - this.tag.setDynamicAttribute(null, "type", "email"); - fail("Expected exception"); - } - catch (IllegalArgumentException e) { - assertEquals("Attribute type=\"email\" is not allowed", e.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.tag.setDynamicAttribute(null, "type", "email")) + .withMessage("Attribute type=\"email\" is not allowed"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java index 5128fd3a66d..b3afa594433 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java @@ -46,10 +46,10 @@ import org.springframework.util.ObjectUtils; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * @author Thomas Risberg @@ -677,14 +677,9 @@ public class CheckboxesTagTests extends AbstractFormTagTests { @Test public void withNullValue() throws Exception { - try { - this.tag.setPath("name"); - this.tag.doStartTag(); - fail("Should not be able to render with a null value when binding to a non-boolean."); - } - catch (IllegalArgumentException ex) { - // success - } + this.tag.setPath("name"); + assertThatIllegalArgumentException().as("null value binding to a non-boolean").isThrownBy( + this.tag::doStartTag); } @Test @@ -733,13 +728,9 @@ public class CheckboxesTagTests extends AbstractFormTagTests { @Test public void dynamicTypeAttribute() throws JspException { - try { - this.tag.setDynamicAttribute(null, "type", "email"); - fail("Expected exception"); - } - catch (IllegalArgumentException e) { - assertEquals("Attribute type=\"email\" is not allowed", e.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.tag.setDynamicAttribute(null, "type", "email")) + .withMessage("Attribute type=\"email\" is not allowed"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index a05b5f2520e..ecc79ffdc0c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -25,11 +25,11 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.servlet.support.RequestDataValueProcessor; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; /** @@ -219,14 +219,9 @@ public class FormTagTests extends AbstractHtmlElementTagTests { @Test public void withNullResolvedCommand() throws Exception { - try { - tag.setModelAttribute(null); - tag.doStartTag(); - fail("Must not be able to have a command name that resolves to null"); - } - catch (IllegalArgumentException ex) { - // expected - } + tag.setModelAttribute(null); + assertThatIllegalArgumentException().isThrownBy( + tag::doStartTag); } /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java index a8d53148937..78cc194590c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java @@ -24,9 +24,9 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BeanPropertyBindingResult; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -86,13 +86,9 @@ public class HiddenInputTagTests extends AbstractFormTagTests { @Test public void dynamicTypeAttribute() throws JspException { - try { - this.tag.setDynamicAttribute(null, "type", "email"); - fail("Expected exception"); - } - catch (IllegalArgumentException e) { - assertEquals("Attribute type=\"email\" is not allowed", e.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.tag.setDynamicAttribute(null, "type", "email")) + .withMessage("Attribute type=\"email\" is not allowed"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java index 4dac38ba922..3ebea34db9d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java @@ -28,9 +28,9 @@ import org.springframework.web.servlet.support.BindStatus; import org.springframework.web.servlet.tags.BindTag; import org.springframework.web.servlet.tags.NestedPathTag; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -360,24 +360,16 @@ public class InputTagTests extends AbstractFormTagTests { @Test public void dynamicTypeRadioAttribute() throws JspException { - try { - this.tag.setDynamicAttribute(null, "type", "radio"); - fail("Expected exception"); - } - catch (IllegalArgumentException e) { - assertEquals("Attribute type=\"radio\" is not allowed", e.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.tag.setDynamicAttribute(null, "type", "radio")) + .withMessage("Attribute type=\"radio\" is not allowed"); } @Test public void dynamicTypeCheckboxAttribute() throws JspException { - try { - this.tag.setDynamicAttribute(null, "type", "checkbox"); - fail("Expected exception"); - } - catch (IllegalArgumentException e) { - assertEquals("Attribute type=\"checkbox\" is not allowed", e.getMessage()); - } + assertThatIllegalArgumentException().isThrownBy(() -> + this.tag.setDynamicAttribute(null, "type", "checkbox")) + .withMessage("Attribute type=\"checkbox\" is not allowed"); } protected final void assertTagClosed(String output) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java index 56195807f21..e644ca4d353 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java @@ -35,9 +35,9 @@ import org.springframework.util.StringUtils; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.web.servlet.support.BindStatus; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Rob Harrop @@ -199,13 +199,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests { this.tag.setParent(null); this.tag.setValue("foo"); this.tag.setLabel("Foo"); - try { - tag.doStartTag(); - fail("Must not be able to use