From 0fe9832213515bdf96f4865084c12209b527243d Mon Sep 17 00:00:00 2001 From: Tran Ngoc Nhan Date: Wed, 16 Jul 2025 19:23:29 +0700 Subject: [PATCH 1/2] Use `assertThatException` for exception test Signed-off-by: Tran Ngoc Nhan --- .../SimpleMessageConverterTests.java | 13 ++-- .../EnableRabbitIntegrationTests.java | 33 ++++----- .../config/ListenerContainerParserTests.java | 16 ++--- .../MismatchedQueueDeclarationTests.java | 16 ++--- .../ConnectionFactoryLifecycleTests.java | 13 ++-- .../rabbit/connection/SSLConnectionTests.java | 29 +++----- .../amqp/rabbit/core/RabbitAdminTests.java | 20 ++---- .../amqp/rabbit/core/RabbitTemplateTests.java | 13 ++-- ...BlockingQueueConsumerIntegrationTests.java | 13 ++-- .../rabbit/listener/ErrorHandlerTests.java | 70 ++++++------------- .../JavaConfigFixedReplyQueueTests.java | 36 +++++----- .../MethodRabbitListenerEndpointTests.java | 17 ++--- ...RecovererWithConfirmsIntegrationTests.java | 17 +++-- ...bitTransactionManagerIntegrationTests.java | 33 ++++----- 14 files changed, 126 insertions(+), 213 deletions(-) diff --git a/spring-amqp/src/test/java/org/springframework/amqp/support/converter/SimpleMessageConverterTests.java b/spring-amqp/src/test/java/org/springframework/amqp/support/converter/SimpleMessageConverterTests.java index 6f77ca9b7b..3af929832e 100644 --- a/spring-amqp/src/test/java/org/springframework/amqp/support/converter/SimpleMessageConverterTests.java +++ b/spring-amqp/src/test/java/org/springframework/amqp/support/converter/SimpleMessageConverterTests.java @@ -27,12 +27,13 @@ import org.springframework.amqp.core.MessageProperties; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; /** * @author Mark Fisher * @author Gary Russell + * @author Ngoc Nhan */ public class SimpleMessageConverterTests extends AllowedListDeserializingMessageConverterTests { @@ -158,13 +159,9 @@ public void notConvertible() { class Foo { } - try { - new SimpleMessageConverter().toMessage(new Foo(), new MessageProperties()); - fail("Expected exception"); - } - catch (IllegalArgumentException e) { - assertThat(e.getMessage()).contains("SimpleMessageConverter only supports String, byte[] and Serializable payloads, received:"); - } + assertThatIllegalArgumentException() + .isThrownBy(() -> new SimpleMessageConverter().toMessage(new Foo(), new MessageProperties())) + .withMessageContaining("SimpleMessageConverter only supports String, byte[] and Serializable payloads, received:"); } } diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java index 85d3e5c0f6..0fab9d3d43 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java @@ -143,7 +143,7 @@ import org.springframework.validation.annotation.Validated; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatException; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willAnswer; @@ -158,6 +158,7 @@ * @author Artem Bilan * @author Gary Russell * @author Mohammad Hewedy + * @author Ngoc Nhan * * @since 1.4 */ @@ -861,13 +862,10 @@ public void deadLetterOnDefaultExchange() { @DirtiesContext public void returnExceptionWithRethrowAdapter() { this.rabbitTemplate.setMessageConverter(new RemoteInvocationAwareMessageConverterAdapter()); - try { - this.rabbitTemplate.convertSendAndReceive("test.return.exceptions", "foo"); - fail("ExpectedException"); - } - catch (Exception e) { - assertThat(e.getCause().getMessage()).isEqualTo("return this"); - } + assertThatException() + .isThrownBy(() -> this.rabbitTemplate.convertSendAndReceive("test.return.exceptions", "foo")) + .havingCause() + .withMessage("return this"); } @Test @@ -879,16 +877,15 @@ public void listenerErrorHandler() { @DirtiesContext public void listenerErrorHandlerException() { this.rabbitTemplate.setMessageConverter(new RemoteInvocationAwareMessageConverterAdapter()); - try { - this.rabbitTemplate.convertSendAndReceive("test.pojo.errors2", "foo"); - fail("ExpectedException"); - } - catch (Exception e) { - assertThat(e.getCause().getMessage()).isEqualTo("from error handler"); - assertThat(e.getCause().getCause().getMessage()).isEqualTo("return this"); - EnableRabbitConfig config = this.context.getBean(EnableRabbitConfig.class); - assertThat(config.errorHandlerChannel).isNotNull(); - } + assertThatException() + .isThrownBy(() -> this.rabbitTemplate.convertSendAndReceive("test.pojo.errors2", "foo")) + .satisfies(ex -> { + + assertThat(ex.getCause().getMessage()).isEqualTo("from error handler"); + assertThat(ex.getCause().getCause().getMessage()).isEqualTo("return this"); + EnableRabbitConfig config = this.context.getBean(EnableRabbitConfig.class); + assertThat(config.errorHandlerChannel).isNotNull(); + }); } @Test diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/ListenerContainerParserTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/ListenerContainerParserTests.java index e740aff899..c1853cc3e3 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/ListenerContainerParserTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/ListenerContainerParserTests.java @@ -44,12 +44,13 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Mark Fisher * @author Gary Russell * @author Artem Bilan + * @author Ngoc Nhan */ public class ListenerContainerParserTests { @@ -224,14 +225,11 @@ public void testAnonParent() { @Test public void testIncompatibleTxAtts() { - try { - new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-fail-context.xml", getClass()).close(); - fail("Parse exception expected"); - } - catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage().startsWith( - "Configuration problem: Listener Container - cannot set channel-transacted with acknowledge='NONE'")).isTrue(); - } + + String path = getClass().getSimpleName() + "-fail-context.xml"; + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> new ClassPathXmlApplicationContext(path, getClass()).close()) + .withMessageStartingWith("Configuration problem: Listener Container - cannot set channel-transacted with acknowledge='NONE'"); } @Test diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/MismatchedQueueDeclarationTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/MismatchedQueueDeclarationTests.java index ab9c5ada69..6a40ee6d26 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/MismatchedQueueDeclarationTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/MismatchedQueueDeclarationTests.java @@ -31,11 +31,12 @@ import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatException; /** * @author Gary Russell * @author Gunnar Hillert + * @author Ngoc Nhan * @since 1.2 * */ @@ -85,14 +86,11 @@ public void testAdminFailsWithMismatchedQueue() throws Exception { env.addActiveProfile("ttl"); context.setEnvironment(env); context.refresh(); - channel = this.connectionFactory.createConnection().createChannel(false); - try { - context.getBean(CachingConnectionFactory.class).createConnection(); - fail("Expected exception - basic admin fails with mismatched declarations"); - } - catch (Exception e) { - assertThat(e.getCause().getCause().getMessage().contains("inequivalent arg 'x-message-ttl'")).isTrue(); - } + this.connectionFactory.createConnection().createChannel(false); + assertThatException().isThrownBy(context.getBean(CachingConnectionFactory.class)::createConnection) + .satisfies(ex -> { + assertThat(ex.getCause().getCause().getMessage()).contains("inequivalent arg 'x-message-ttl'"); + }); assertThat(this.admin.getQueueProperties("mismatch.foo")).isNotNull(); assertThat(this.admin.getQueueProperties("mismatch.bar")).isNull(); context.close(); diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/ConnectionFactoryLifecycleTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/ConnectionFactoryLifecycleTests.java index ad4532932b..d963150a62 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/ConnectionFactoryLifecycleTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/ConnectionFactoryLifecycleTests.java @@ -40,11 +40,12 @@ import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Gary Russell * @author Artem Bilan + * @author Ngoc Nhan * * @since 1.5.3 * @@ -60,13 +61,9 @@ public void testConnectionFactoryAvailableDuringStop() { context.close(); assertThat(myLifecycle.isRunning()).isFalse(); assertThat(TestUtils.getPropertyValue(cf, "stopped", Boolean.class)).isTrue(); - try { - cf.createConnection(); - fail("Expected exception"); - } - catch (AmqpApplicationContextClosedException e) { - assertThat(e.getMessage()).contains("The ApplicationContext is closed"); - } + assertThatExceptionOfType(AmqpApplicationContextClosedException.class) + .isThrownBy(cf::createConnection) + .withMessageContaining("The ApplicationContext is closed"); } @Test diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/SSLConnectionTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/SSLConnectionTests.java index 35f001ca6a..f1642d22c9 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/SSLConnectionTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/connection/SSLConnectionTests.java @@ -37,7 +37,7 @@ import org.springframework.core.io.ClassPathResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -50,6 +50,7 @@ * @author Gary Russell * @author Heath Abelson * @author Hareendran + * @author Ngoc Nhan * * @since 1.4.4 * @@ -221,16 +222,9 @@ public void testTypeProps() { RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean(); fb.setSslPropertiesLocation(new ClassPathResource("ssl.properties")); fb.afterPropertiesSet(); - try { - fb.setUpSSL(); - //Here we make sure the exception is thrown because setUpSSL() will fail. - // But we only care about having it load the props - fail("setupSSL should fail"); - } - catch (Exception e) { - assertThat(fb.getKeyStoreType()).isEqualTo("foo"); - assertThat(fb.getTrustStoreType()).isEqualTo("bar"); - } + assertThatException().isThrownBy(fb::setUpSSL); + assertThat(fb.getKeyStoreType()).isEqualTo("foo"); + assertThat(fb.getTrustStoreType()).isEqualTo("bar"); } @Test @@ -249,16 +243,9 @@ public void testTypeSettersOverrideProps() { fb.afterPropertiesSet(); fb.setKeyStoreType("alice"); fb.setTrustStoreType("bob"); - try { - fb.setUpSSL(); - // Here we make sure the exception is thrown because setUpSSL() will fail. - //But we only care about having it load the props - fail("setupSSL should fail"); - } - catch (Exception e) { - assertThat(fb.getKeyStoreType()).isEqualTo("alice"); - assertThat(fb.getTrustStoreType()).isEqualTo("bob"); - } + assertThatException().isThrownBy(fb::setUpSSL); + assertThat(fb.getKeyStoreType()).isEqualTo("alice"); + assertThat(fb.getTrustStoreType()).isEqualTo("bob"); } @Test diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitAdminTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitAdminTests.java index 6631045d03..f99a5652b5 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitAdminTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitAdminTests.java @@ -67,9 +67,9 @@ import org.springframework.retry.support.RetryTemplate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -92,6 +92,7 @@ * @author Gary Russell * @author Artem Bilan * @author Artem Yakshin + * @author Ngoc Nhan * * @since 1.4.1 * @@ -102,13 +103,8 @@ public class RabbitAdminTests extends NeedsManagementTests { @Test public void testSettingOfNullConnectionFactory() { ConnectionFactory connectionFactory = null; - try { - new RabbitAdmin(connectionFactory); - fail("should have thrown IllegalArgumentException when ConnectionFactory is null."); - } - catch (IllegalArgumentException e) { - assertThat(e.getMessage()).isEqualTo("ConnectionFactory must not be null"); - } + assertThatIllegalArgumentException().isThrownBy(() -> new RabbitAdmin(connectionFactory)) + .withMessage("ConnectionFactory must not be null"); } @Test @@ -266,13 +262,7 @@ public void testAvoidHangAMQP_508() { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); RabbitAdmin admin = new RabbitAdmin(cf); String longName = new String(new byte[300]).replace('\u0000', 'x'); - try { - admin.declareQueue(new Queue(longName)); - fail("expected exception"); - } - catch (@SuppressWarnings("unused") Exception e) { - // NOSONAR - } + assertThatException().isThrownBy(() -> admin.declareQueue(new Queue(longName))); String goodName = "foobar"; admin.declareQueue(new Queue(goodName)); assertThat(admin.getQueueProperties(longName)).isNull(); diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitTemplateTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitTemplateTests.java index 9c53e7f932..a833a55982 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitTemplateTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/core/RabbitTemplateTests.java @@ -85,7 +85,6 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyMap; @@ -104,6 +103,7 @@ * @author Gary Russell * @author Artem Bilan * @author Mohammad Hewedy + * @author Ngoc Nhan * @since 1.0.1 * */ @@ -492,13 +492,10 @@ public void testShutdownWhileWaitingForReply() throws Exception { } listener.get().shutdownCompleted(new ShutdownSignalException(true, false, null, null)); }); - try { - template.doSendAndReceiveWithTemporary("foo", "bar", input, null); - fail("Expected exception"); - } - catch (AmqpException e) { - assertThat(e.getCause()).isInstanceOf(ShutdownSignalException.class); - } + + assertThatExceptionOfType(AmqpException.class) + .isThrownBy(() -> template.doSendAndReceiveWithTemporary("foo", "bar", input, null)) + .withCauseInstanceOf(ShutdownSignalException.class); exec.shutdownNow(); } diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumerIntegrationTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumerIntegrationTests.java index 1e70617a37..62c68de66b 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumerIntegrationTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumerIntegrationTests.java @@ -36,12 +36,13 @@ import org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Dave Syer * @author Gunnar Hillert * @author Gary Russell + * @author Ngoc Nhan * @since 1.0 * */ @@ -98,13 +99,9 @@ public void testAvoidHangAMQP_508() { BlockingQueueConsumer blockingQueueConsumer = new BlockingQueueConsumer(connectionFactory, new DefaultMessagePropertiesConverter(), new ActiveObjectCounter(), AcknowledgeMode.AUTO, true, 1, longName, "foobar"); - try { - blockingQueueConsumer.start(); - fail("expected exception"); - } - catch (FatalListenerStartupException e) { - assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); - } + assertThatExceptionOfType(FatalListenerStartupException.class) + .isThrownBy(blockingQueueConsumer::start) + .withCauseInstanceOf(IllegalArgumentException.class); connectionFactory.destroy(); } diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/ErrorHandlerTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/ErrorHandlerTests.java index 5d54b124fe..4a2b936aba 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/ErrorHandlerTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/ErrorHandlerTests.java @@ -31,7 +31,7 @@ import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException; import org.springframework.messaging.handler.annotation.support.MethodArgumentTypeMismatchException; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.willDoNothing; @@ -41,6 +41,7 @@ /** * @author Gary Russell * @author Artem Bilan + * @author Ngoc Nhan * * @since 1.6 * @@ -56,67 +57,40 @@ public void testFatalsAreRejected() throws Exception { handler.handleError(new ListenerExecutionFailedException("intended", new RuntimeException(), new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties()))); - try { - handler.handleError(new ListenerExecutionFailedException("intended", new MessageConversionException(""), - new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties()))); - fail("Expected exception"); - } - catch (AmqpRejectAndDontRequeueException e) { - } + assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class) + .isThrownBy(() -> handler.handleError(new ListenerExecutionFailedException("intended", + new MessageConversionException(""), + new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties())))); - try { - handler.handleError(new ListenerExecutionFailedException("intended", - new org.springframework.messaging.converter.MessageConversionException(""), - new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties()))); - fail("Expected exception"); - } - catch (AmqpRejectAndDontRequeueException e) { - } + assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class) + .isThrownBy(() -> handler.handleError(new ListenerExecutionFailedException("intended", + new org.springframework.messaging.converter.MessageConversionException(""), + new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties())))); Message message = mock(Message.class); MethodParameter mp = new MethodParameter(Foo.class.getMethod("foo", String.class), 0); - try { - handler.handleError(new ListenerExecutionFailedException("intended", - new MethodArgumentNotValidException(message, mp), - new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties()))); - fail("Expected exception"); - } - catch (AmqpRejectAndDontRequeueException e) { - } - - try { - handler.handleError(new ListenerExecutionFailedException("intended", - new MethodArgumentTypeMismatchException(message, mp, ""), - new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties()))); - fail("Expected exception"); - } - catch (AmqpRejectAndDontRequeueException e) { - } + assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class) + .isThrownBy(() -> handler.handleError(new ListenerExecutionFailedException("intended", + new MethodArgumentNotValidException(message, mp), + new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties())))); + + assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class) + .isThrownBy(() -> handler.handleError(new ListenerExecutionFailedException("intended", + new MethodArgumentTypeMismatchException(message, mp, ""), + new org.springframework.amqp.core.Message("".getBytes(), new MessageProperties())))); } @Test public void testSimple() { Throwable cause = new ClassCastException(); - try { - doTest(cause); - fail("Expected exception"); - } - catch (AmqpRejectAndDontRequeueException e) { - // noop - } + assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class).isThrownBy(() -> doTest(cause)); } @Test public void testMessagingException() { Throwable cause = new MessageHandlingException(null, "test", new MessageHandlingException(null, "test", new ClassCastException())); - try { - doTest(cause); - fail("Expected exception"); - } - catch (AmqpRejectAndDontRequeueException e) { - // noop - } + assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class).isThrownBy(() -> doTest(cause)); } private void doTest(Throwable cause) { @@ -124,7 +98,7 @@ private void doTest(Throwable cause) { handler.handleError( new ListenerExecutionFailedException("test", cause, new org.springframework.amqp.core.Message(new byte[0], - new MessageProperties()))); + new MessageProperties()))); } private static final class Foo { diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/JavaConfigFixedReplyQueueTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/JavaConfigFixedReplyQueueTests.java index 70a7b69e67..654f4ba726 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/JavaConfigFixedReplyQueueTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/JavaConfigFixedReplyQueueTests.java @@ -44,13 +44,15 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * NOTE: This class is referenced in the reference documentation; if it is changed/moved, be * sure to update that documentation. * * @author Gary Russell + * @author Ngoc Nhan * @since 1.3 */ @@ -91,29 +93,21 @@ public void testReplyContainer() { @Test public void testReplyNoContainerNoTimeout() { - try { - this.fixedReplyQRabbitTemplateNoReplyContainer.convertSendAndReceive("foo"); - fail("expected exeption"); - } - catch (IllegalStateException e) { - assertThat(e.getMessage()).contains("RabbitTemplate is not configured as MessageListener - " - + "cannot use a 'replyAddress'"); - } + + assertThatIllegalStateException() + .isThrownBy(() -> this.fixedReplyQRabbitTemplateNoReplyContainer.convertSendAndReceive("foo")) + .withMessageContaining("RabbitTemplate is not configured as MessageListener - cannot use a 'replyAddress'"); } @Test public void testMismatchedQueue() { - try { - this.replyListenerContainerWrongQueue.start(); - fail("expected exeption"); - } - catch (UncategorizedAmqpException e) { - Throwable t = e.getCause(); - assertThat(t).isInstanceOf(IllegalStateException.class); - assertThat(t.getMessage()).contains("Listener expects us to be listening on '[" - + TestUtils.getPropertyValue(this.fixedReplyQRabbitTemplateWrongQueue, "replyAddress") - + "]'; our queues: " + Arrays.asList(this.replyListenerContainerWrongQueue.getQueueNames())); - } + + assertThatExceptionOfType(UncategorizedAmqpException.class) + .isThrownBy(() -> this.replyListenerContainerWrongQueue.start()) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("Listener expects us to be listening on '[" + + TestUtils.getPropertyValue(this.fixedReplyQRabbitTemplateWrongQueue, "replyAddress") + + "]'; our queues: " + Arrays.asList(this.replyListenerContainerWrongQueue.getQueueNames())); } @Configuration @@ -259,7 +253,9 @@ public static class PojoListener { public String handleMessage(String foo) { return foo.toUpperCase(); } + } + } } diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/MethodRabbitListenerEndpointTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/MethodRabbitListenerEndpointTests.java index 1779775ff6..6fde2b6379 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/MethodRabbitListenerEndpointTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/MethodRabbitListenerEndpointTests.java @@ -56,9 +56,9 @@ import org.springframework.validation.annotation.Validated; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -68,6 +68,7 @@ * @author Stephane Nicoll * @author Artem Bilan * @author Gary Russell + * @author Ngoc Nhan */ public class MethodRabbitListenerEndpointTests { @@ -254,16 +255,10 @@ public void processAndReplyWithMessageAndStringReply() throws Exception { org.springframework.amqp.core.Message message = MessageTestUtils.createTextMessage(body, new MessageProperties()); - try { - processAndReply(listener, message, "fooQueue", "", false, null); - fail("Should have fail. Not converter and the reply is not a message"); - } - catch (ReplyFailureException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isNotNull(); - assertThat(cause.getClass()).isEqualTo(MessageConversionException.class); - assertThat(ex.getMessage().contains("foo")).isTrue(); // exception holds the content of the reply - } + assertThatExceptionOfType(ReplyFailureException.class) + .isThrownBy(() -> processAndReply(listener, message, "fooQueue", "", false, null)) + .withCauseInstanceOf(MessageConversionException.class) + .withMessageContaining("foo"); assertDefaultListenerMethodInvocation(); } diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/retry/RepublishMessageRecovererWithConfirmsIntegrationTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/retry/RepublishMessageRecovererWithConfirmsIntegrationTests.java index 65f8317181..1d5c437371 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/retry/RepublishMessageRecovererWithConfirmsIntegrationTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/retry/RepublishMessageRecovererWithConfirmsIntegrationTests.java @@ -36,10 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; /** * @author Gary Russell + * @author Ngoc Nhan * @since 2.0.5 * */ @@ -86,14 +86,13 @@ void testCorrelatedNotRoutable() { template.setMandatory(true); RepublishMessageRecovererWithConfirms recoverer = new RepublishMessageRecovererWithConfirms(template, "", "bad.route", ConfirmType.CORRELATED); - try { - recoverer.recover(MessageBuilder.withBody("foo".getBytes()).build(), new RuntimeException()); - fail("Expected exception"); - } - catch (AmqpMessageReturnedException ex) { - assertThat(ex.getReturnedMessage().getBody()).isEqualTo("foo".getBytes()); - assertThat(ex.getReplyText()).isEqualTo("NO_ROUTE"); - } + assertThatExceptionOfType(AmqpMessageReturnedException.class) + .isThrownBy(() -> recoverer.recover(MessageBuilder.withBody("foo".getBytes()).build(), new RuntimeException())) + .satisfies(ex -> { + + assertThat(ex.getReturnedMessage().getBody()).isEqualTo("foo".getBytes()); + assertThat(ex.getReplyText()).isEqualTo("NO_ROUTE"); + }); ccf.destroy(); } diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/transaction/RabbitTransactionManagerIntegrationTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/transaction/RabbitTransactionManagerIntegrationTests.java index 9eeb0f4269..dad4d4cc83 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/transaction/RabbitTransactionManagerIntegrationTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/transaction/RabbitTransactionManagerIntegrationTests.java @@ -27,12 +27,13 @@ import org.springframework.transaction.support.TransactionTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author David Syer * @author Gunnar Hillert * @author Gary Russell + * @author Ngoc Nhan * @since 1.0 * */ @@ -87,16 +88,11 @@ public void testReceiveInTransactionWithRollback() throws Exception { // Makes receive (and send in principle) transactional template.setChannelTransacted(true); template.convertAndSend(ROUTE, "message"); - try { - transactionTemplate.execute(status -> { - template.receiveAndConvert(ROUTE); - throw new PlannedException(); - }); - fail("Expected PlannedException"); - } - catch (PlannedException e) { - // Expected - } + assertThatExceptionOfType(PlannedException.class) + .isThrownBy(() -> transactionTemplate.execute(status -> { + template.receiveAndConvert(ROUTE); + throw new PlannedException(); + })); String result = (String) template.receiveAndConvert(ROUTE); assertThat(result).isEqualTo("message"); result = (String) template.receiveAndConvert(ROUTE); @@ -119,16 +115,11 @@ public void testSendInTransaction() throws Exception { @Test public void testSendInTransactionWithRollback() throws Exception { template.setChannelTransacted(true); - try { - transactionTemplate.execute(status -> { - template.convertAndSend(ROUTE, "message"); - throw new PlannedException(); - }); - fail("Expected PlannedException"); - } - catch (PlannedException e) { - // Expected - } + assertThatExceptionOfType(PlannedException.class) + .isThrownBy(() -> transactionTemplate.execute(status -> { + template.convertAndSend(ROUTE, "message"); + throw new PlannedException(); + })); String result = (String) template.receiveAndConvert(ROUTE); assertThat(result).isEqualTo(null); } From 97fb9aec40aee1bc3c7c3c6746a344e08adb29e9 Mon Sep 17 00:00:00 2001 From: Tran Ngoc Nhan Date: Wed, 16 Jul 2025 21:46:15 +0700 Subject: [PATCH 2/2] Addressing PR review Signed-off-by: Tran Ngoc Nhan --- .../amqp/rabbit/annotation/EnableRabbitIntegrationTests.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java index 0fab9d3d43..ab07aa0506 100644 --- a/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java +++ b/spring-rabbit/src/test/java/org/springframework/amqp/rabbit/annotation/EnableRabbitIntegrationTests.java @@ -883,9 +883,9 @@ public void listenerErrorHandlerException() { assertThat(ex.getCause().getMessage()).isEqualTo("from error handler"); assertThat(ex.getCause().getCause().getMessage()).isEqualTo("return this"); - EnableRabbitConfig config = this.context.getBean(EnableRabbitConfig.class); - assertThat(config.errorHandlerChannel).isNotNull(); }); + EnableRabbitConfig config = this.context.getBean(EnableRabbitConfig.class); + assertThat(config.errorHandlerChannel).isNotNull(); } @Test