You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by or...@apache.org on 2026/01/25 14:04:14 UTC

(camel) branch main updated (7590e44d6db3 -> 0d793d3964c3)

This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


    from 7590e44d6db3 camel-core - Add missing function
     new d259f6390e69 CAMEL-21196: modernize exception-based assertions in camel-avro
     new 95c697b9ca6f CAMEL-21196: modernize exception-based assertions in camel-exec
     new 562ff5de8089 CAMEL-21196: modernize exception-based assertions in camel-groovy
     new f5b495a23c7a CAMEL-21196: modernize exception-based assertions in camel-graphql
     new f14d1151a337 CAMEL-21196: modernize exception-based assertions in camel-crypto
     new c96243b9738d CAMEL-21196: modernize exception-based assertions in camel-jq
     new 5bbd9175b26d CAMEL-21196: modernize exception-based assertions in camel-csimple-joor
     new 4316e3eec043 CAMEL-21196: modernize exception-based assertions in camel-univocity-parsers
     new df4bf3cdc87b CAMEL-21196: modernize exception-based assertions in camel-test
     new 8e28eda0b1dc CAMEL-21196: modernize exception-based assertions in camel-keycloak
     new dd2d9bd94f43 CAMEL-21196: modernize exception-based assertions in camel-mllp
     new cf032e9a2026 CAMEL-21196: modernize exception-based assertions in camel-olingo4
     new dfa0835ae888 CAMEL-21196: modernize exception-based assertions in camel-platform-http-vertx
     new 76e93723e6d0 CAMEL-21196: modernize exception-based assertions in camel-sjms
     new 5b979e643088 CAMEL-21196: Modernize exception-based assertions in camel-aws
     new b64a59c08f78 CAMEL-21196: modernize exception-based assertions in camel-jpa
     new 2f96d33ea08f CAMEL-21196: modernize exception-based assertions in camel-jaxb
     new fa4eba3ff2c1 CAMEL-21196: modernize exception-based assertions in camel-jdbc
     new 812660e0bb00 CAMEL-21196: modernize exception-based assertions in camel-jmx
     new 7387164ff3ba CAMEL-21196: modernize exception-based assertions in camel-fhir
     new 83996de6c327 CAMEL-21196: modernize exception-based assertions in camel-dns
     new 85d808b3123d CAMEL-21196: modernize exception-based assertions in camel-file-watch
     new c9639f77466d CAMEL-21196: modernize exception-based assertions in camel-guava-eventbus
     new 1683285ee7ca CAMEL-21196: modernize exception-based assertions in camel-hazelcast
     new a1c4bd60a26d CAMEL-21196: modernize exception-based assertions in camel-servlet
     new d08757e3220c CAMEL-21196: modernize exception-based assertions in camel-jt400
     new 3c44341732fc CAMEL-21196: modernize exception-based assertions in camel-protobuf
     new c197fbc53422 CAMEL-21196: modernize exception-based assertions in camel-undertow
     new 6f55a3eebad4 CAMEL-21196: modernize exception-based assertions in camel-jira
     new 7d7c9f1d6fff CAMEL-21196: modernize exception-based assertions in camel-sjms2
     new a7109a345b26 CAMEL-21196: modernize exception-based assertions in camel-workday
     new 5cf20290ab7e CAMEL-21196: modernize exception-based assertions in camel-sql
     new 5232cd3388a1 CAMEL-21196: modernize exception-based assertions in camel-xslt-saxon
     new 5a4350f45504 CAMEL-21196: modernize exception-based assertions in camel-thrift
     new 049b6270019f CAMEL-21196: modernize exception-based assertions in camel-platform-http-vertx
     new 0d793d3964c3 CAMEL-21196: modernize exception-based assertions in camel-clickup

The 36 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../avro/AvroMarshalAndUnmarshalTest.java          |   9 +-
 .../KinesisConsumerClosedShardWithFailTest.java    |   8 +-
 .../bean/validator/BeanValidatorRouteTest.java     | 170 +++++-----
 ...indySimpleCsvMandatoryFieldsUnmarshallTest.java |  19 +-
 .../BindyFixedLengthDelimitedFieldTest.java        |  38 +--
 .../dynamic/BindyFixedLengthDynamicFieldTest.java  |  14 +-
 .../clickup/ClickUpWebhookRegistrationTest.java    |   2 +-
 .../converter/crypto/CryptoDataFormatTest.java     |  12 +-
 .../csimple/joor/OriginalSimpleOperatorTest.java   | 114 +++----
 .../language/csimple/joor/OriginalSimpleTest.java  | 346 +++++++--------------
 .../component/dns/DnsIpEndpointSpringTest.java     |  18 +-
 .../camel/component/dns/DnsIpEndpointTest.java     |  18 +-
 .../component/dns/DnsIpHeaderTransferTest.java     |  18 +-
 .../component/dns/DnsLookupEndpointSpringTest.java |  18 +-
 .../camel/component/dns/DnsLookupEndpointTest.java |  18 +-
 .../camel/component/exec/ExecJava8IssueTest.java   |   6 +-
 .../FhirJsonDataformatErrorHandlerTest.java        |  12 +-
 .../FhirXmlDataformatErrorHandlerTest.java         |  12 +-
 .../FhirJsonDataformatErrorHandlerSpringTest.java  |  12 +-
 .../FhirXmlDataformatErrorHandlerSpringTest.java   |  12 +-
 .../file/watch/FileWatchComponentNegativeTest.java |   8 +-
 .../component/graphql/GraphqlComponentTest.java    |  15 +-
 .../language/groovy/GroovyExpressionTest.java      |  14 +-
 .../camel/language/groovy/GroovyLanguageTest.java  |  12 +-
 .../camel/processor/groovy/GroovyLogEipTest.java   |  10 +-
 .../GuavaEventBusConsumerConfigurationTest.java    |  12 +-
 .../hazelcast/HazelcastErrorMessagesTest.java      |  22 +-
 .../hazelcast/HazelcastSedaConfigurationTest.java  |  10 +-
 .../camel/component/hl7/HL7ValidateTest.java       |  32 +-
 .../camel/jaxb/CamelJaxbFallbackConverterTest.java |  31 +-
 .../jaxb/JaxbDataFormatMustBeJAXBElementTest.java  |  16 +-
 .../camel/component/jdbc/JdbcOptionsTest.java      |  14 +-
 .../jira/producer/AddIssueLinkProducerTest.java    |  35 +--
 .../jira/producer/AddWorkLogProducerTest.java      |  35 +--
 .../jira/producer/FetchCommentsProducerTest.java   |  13 +-
 .../jira/producer/FetchIssueProducerTest.java      |  13 +-
 .../camel/component/jmx/JMXComponentTest.java      |  32 +-
 .../camel/component/jmx/JMXEndpointTest.java       |  90 +++---
 .../jmx/JMXRobustRemoteConnectionTest.java         |  14 +-
 .../camel/processor/jpa/JpaProducerNoBodyTest.java |  12 +-
 .../camel/language/jq/JqLanguageValidateTest.java  |  10 +-
 .../Jt400ComponentDefaultConnectionPoolTest.java   |  14 +-
 ...00ComponentDefaultSecureConnectionPoolTest.java |  14 +-
 .../camel/component/jt400/Jt400ComponentTest.java  |  10 +-
 .../security/KeycloakSecurityHelperTest.java       |  22 +-
 ...nAndHeaderRequiresClientAuthenticationTest.java |   8 +-
 .../internal/MllpSocketBufferReadFromTest.java     |  26 +-
 .../mllp/internal/MllpSocketBufferTest.java        |  10 +-
 .../camel/component/olingo4/Olingo4AppAPITest.java |  13 +-
 ...PlatformHttpRestOpenApiConsumerRestDslTest.java |  32 +-
 .../vertx/PlatformHttpRestOpenApiConsumerTest.java |  34 +-
 .../ProtobufMarshalAndUnmarshalSpringTest.java     |  10 +-
 .../protobuf/ProtobufMarshalAndUnmarshalTest.java  |  10 +-
 .../servlet/MultiServletConsumerTest.java          |  20 +-
 .../component/servlet/ServletChoiceBeanTest.java   |  10 +-
 .../sjms/producer/QueueProducerQoSTest.java        |  14 +-
 .../sjms/tx/TransactedQueueInOutProducerTest.java  |  10 +-
 .../sjms/tx/TransactedQueueProducerTest.java       |  10 +-
 .../sjms/tx/TransactedTopicProducerTest.java       |  10 +-
 .../camel/component/sjms2/Sjms2EndpointTest.java   |  37 +--
 .../TransactionalClientDataSourceAsyncTest.java    |  16 +-
 ...sactionalClientDataSourceNotTransactedTest.java |  14 +-
 .../TransactionalClientDataSourceTest.java         |  16 +-
 ...ourceWithOnExceptionHandledAndRollbackTest.java |   9 +-
 ...lientDataSourceWithOnExceptionRollbackTest.java |  16 +-
 ...ctionalClientDataSourceWithOnExceptionTest.java |  16 +-
 .../TransactionalClientWithRollbackTest.java       |  12 +-
 .../SpringCamelContextStartingFailedEventTest.java |  18 +-
 .../spring/processor/SpringFilterNoChildTest.java  |  18 +-
 .../processor/SpringTryCatchMisconfiguredTest.java |  32 +-
 .../sql/SqlProducerNamedParameterNotExistTest.java |  20 +-
 .../apache/camel/component/sql/SqlRouteTest.java   |   3 +-
 .../sql/stored/ProducerBatchInvalidTest.java       |  19 +-
 .../jdbc/JdbcRemoveConfirmOrderAggregateTest.java  |   4 +-
 .../junit5/patterns/AdviceWithNotStartedTest.java  |  10 +-
 .../test/junit5/patterns/AsyncSendMockTest.java    |   9 +-
 .../junit6/patterns/AdviceWithNotStartedTest.java  |  10 +-
 .../test/junit6/patterns/AsyncSendMockTest.java    |   9 +-
 .../thrift/ThriftProducerSecurityTest.java         |  13 +-
 .../component/thrift/ThriftProducerSyncTest.java   |  13 +-
 .../ThriftMarshalAndUnmarshalSpringTest.java       |  21 +-
 .../thrift/ThriftMarshalAndUnmarshalTest.java      |  21 +-
 .../undertow/DefaultUndertowHttpBindingTest.java   |   3 +-
 .../undertow/UndertowConsumerUnregisterTest.java   |  13 +-
 .../component/undertow/UndertowError500Test.java   |  10 +-
 .../undertow/UndertowHandlersSpringTest.java       |  17 +-
 .../component/undertow/UndertowHttp2Test.java      |  14 +-
 .../undertow/UndertowPrefixMatchingTest.java       |  13 +-
 .../undertow/UndertowSuspendResumeTest.java        |  12 +-
 .../rest/RestUndertowHttpBindingModeXmlTest.java   |   9 +-
 .../rest/RestUndertowMethodNotAllowedTest.java     |  24 +-
 .../spi/SecurityProviderHttpHandlerTest.java       |  15 +-
 .../spi/SecurityProviderNoAcceptanceTest.java      |  15 +-
 .../SecurityProviderRolesFromComponentTest.java    |  15 +-
 .../undertow/spi/SecurityProviderTest.java         |  15 +-
 .../spi/SecurityProviderWithoutProviderTest.java   |  15 +-
 .../UniVocityCsvDataFormatUnmarshalSpringTest.java |  16 +-
 .../UniVocityCsvDataFormatUnmarshalTest.java       |  16 +-
 ...niVocityFixedDataFormatUnmarshalSpringTest.java |  16 +-
 .../UniVocityFixedDataFormatUnmarshalTest.java     |  16 +-
 .../UniVocityTsvDataFormatUnmarshalSpringTest.java |  16 +-
 .../UniVocityTsvDataFormatUnmarshalTest.java       |  16 +-
 .../apache/camel/WorkdayCommonAPIProducerTest.java |  27 +-
 .../apache/camel/WorkdayReportProducerTest.java    |  15 +-
 .../component/xslt/SaxonInvalidXsltFileTest.java   |  13 +-
 .../component/xslt/SaxonXsltFeatureRouteTest.java  |  15 +-
 106 files changed, 865 insertions(+), 1450 deletions(-)


(camel) 08/36: CAMEL-21196: modernize exception-based assertions in camel-univocity-parsers

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 4316e3eec043c99d227d5eee4fa49a0bc9febdf1
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:38:36 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-univocity-parsers
    
    Converted try-catch-fail patterns to JUnit 5 assertThrows in 6 test files:
    - UniVocityCsvDataFormatUnmarshalTest
    - UniVocityCsvDataFormatUnmarshalSpringTest
    - UniVocityFixedDataFormatUnmarshalTest
    - UniVocityFixedDataFormatUnmarshalSpringTest
    - UniVocityTsvDataFormatUnmarshalTest
    - UniVocityTsvDataFormatUnmarshalSpringTest
    
    Replaced fail() import with assertThrows and converted all
    try-catch blocks to lambda-based assertThrows calls.
---
 .../UniVocityCsvDataFormatUnmarshalSpringTest.java       | 16 +++-------------
 .../univocity/UniVocityCsvDataFormatUnmarshalTest.java   | 16 +++-------------
 .../UniVocityFixedDataFormatUnmarshalSpringTest.java     | 16 +++-------------
 .../univocity/UniVocityFixedDataFormatUnmarshalTest.java | 16 +++-------------
 .../UniVocityTsvDataFormatUnmarshalSpringTest.java       | 16 +++-------------
 .../univocity/UniVocityTsvDataFormatUnmarshalTest.java   | 16 +++-------------
 6 files changed, 18 insertions(+), 78 deletions(-)

diff --git a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalSpringTest.java b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalSpringTest.java
index e3dde7c022c2..14436dd61f21 100644
--- a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalSpringTest.java
+++ b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalSpringTest.java
@@ -33,8 +33,8 @@ import static org.apache.camel.dataformat.univocity.UniVocityTestHelper.join;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This class tests the unmarshalling of {@link org.apache.camel.dataformat.univocity.UniVocityCsvDataFormat} using the
@@ -110,12 +110,7 @@ public final class UniVocityCsvDataFormatUnmarshalSpringTest extends CamelSpring
         assertEquals(Arrays.asList("A", "B", "C"), body.next());
 
         // Try to remove the element
-        try {
-            body.remove();
-            fail("Should have thrown a UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            // Success
-        }
+        assertThrows(UnsupportedOperationException.class, body::remove);
 
         // Read all the lines
         assertTrue(body.hasNext());
@@ -125,12 +120,7 @@ public final class UniVocityCsvDataFormatUnmarshalSpringTest extends CamelSpring
         assertFalse(body.hasNext());
 
         // Try to read one more element
-        try {
-            body.next();
-            fail("Should have thrown a NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Success
-        }
+        assertThrows(NoSuchElementException.class, body::next);
     }
 
     /**
diff --git a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalTest.java b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalTest.java
index 0759cc6b9d5c..b9c503c04270 100644
--- a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalTest.java
+++ b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatUnmarshalTest.java
@@ -35,8 +35,8 @@ import static org.apache.camel.dataformat.univocity.UniVocityTestHelper.join;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This class tests the unmarshalling of {@link org.apache.camel.dataformat.univocity.UniVocityCsvDataFormat} using the
@@ -112,12 +112,7 @@ public final class UniVocityCsvDataFormatUnmarshalTest extends CamelTestSupport
         assertEquals(Arrays.asList("A", "B", "C"), body.next());
 
         // Try to remove the element
-        try {
-            body.remove();
-            fail("Should have thrown a UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            // Success
-        }
+        assertThrows(UnsupportedOperationException.class, body::remove);
 
         // Read all the lines
         assertTrue(body.hasNext());
@@ -127,12 +122,7 @@ public final class UniVocityCsvDataFormatUnmarshalTest extends CamelTestSupport
         assertFalse(body.hasNext());
 
         // Try to read one more element
-        try {
-            body.next();
-            fail("Should have thrown a NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Success
-        }
+        assertThrows(NoSuchElementException.class, body::next);
     }
 
     /**
diff --git a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalSpringTest.java b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalSpringTest.java
index 1433615e4e16..9ea29a02e539 100644
--- a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalSpringTest.java
+++ b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalSpringTest.java
@@ -33,8 +33,8 @@ import static org.apache.camel.dataformat.univocity.UniVocityTestHelper.join;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This class tests the unmarshalling of {@link UniVocityFixedDataFormat} using the Spring DSL.
@@ -109,12 +109,7 @@ public final class UniVocityFixedDataFormatUnmarshalSpringTest extends CamelSpri
         assertEquals(Arrays.asList("A", "B", "C"), body.next());
 
         // Try to remove the element
-        try {
-            body.remove();
-            fail("Should have thrown a UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            // Success
-        }
+        assertThrows(UnsupportedOperationException.class, body::remove);
 
         // Read all the lines
         assertTrue(body.hasNext());
@@ -124,12 +119,7 @@ public final class UniVocityFixedDataFormatUnmarshalSpringTest extends CamelSpri
         assertFalse(body.hasNext());
 
         // Try to read one more element
-        try {
-            body.next();
-            fail("Should have thrown a NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Success
-        }
+        assertThrows(NoSuchElementException.class, body::next);
     }
 
     /**
diff --git a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalTest.java b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalTest.java
index cc73e718d95e..8122159c3549 100644
--- a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalTest.java
+++ b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityFixedDataFormatUnmarshalTest.java
@@ -35,8 +35,8 @@ import static org.apache.camel.dataformat.univocity.UniVocityTestHelper.join;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This class tests the unmarshalling of {@link UniVocityFixedDataFormat}.
@@ -111,12 +111,7 @@ public final class UniVocityFixedDataFormatUnmarshalTest extends CamelTestSuppor
         assertEquals(Arrays.asList("A", "B", "C"), body.next());
 
         // Try to remove the element
-        try {
-            body.remove();
-            fail("Should have thrown a UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            // Success
-        }
+        assertThrows(UnsupportedOperationException.class, body::remove);
 
         // Read all the lines
         assertTrue(body.hasNext());
@@ -126,12 +121,7 @@ public final class UniVocityFixedDataFormatUnmarshalTest extends CamelTestSuppor
         assertFalse(body.hasNext());
 
         // Try to read one more element
-        try {
-            body.next();
-            fail("Should have thrown a NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Success
-        }
+        assertThrows(NoSuchElementException.class, body::next);
     }
 
     /**
diff --git a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalSpringTest.java b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalSpringTest.java
index 991a0730a862..ad0c032f177a 100644
--- a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalSpringTest.java
+++ b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalSpringTest.java
@@ -33,8 +33,8 @@ import static org.apache.camel.dataformat.univocity.UniVocityTestHelper.join;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This class tests the unmarshalling of {@link org.apache.camel.dataformat.univocity.UniVocityTsvDataFormat} using the
@@ -110,12 +110,7 @@ public final class UniVocityTsvDataFormatUnmarshalSpringTest extends CamelSpring
         assertEquals(Arrays.asList("A", "B", "C"), body.next());
 
         // Try to remove the element
-        try {
-            body.remove();
-            fail("Should have thrown a UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            // Success
-        }
+        assertThrows(UnsupportedOperationException.class, body::remove);
 
         // Read all the lines
         assertTrue(body.hasNext());
@@ -125,12 +120,7 @@ public final class UniVocityTsvDataFormatUnmarshalSpringTest extends CamelSpring
         assertFalse(body.hasNext());
 
         // Try to read one more element
-        try {
-            body.next();
-            fail("Should have thrown a NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Success
-        }
+        assertThrows(NoSuchElementException.class, body::next);
     }
 
     /**
diff --git a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalTest.java b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalTest.java
index b1c886e5f4dd..984209eecf32 100644
--- a/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalTest.java
+++ b/components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTsvDataFormatUnmarshalTest.java
@@ -35,8 +35,8 @@ import static org.apache.camel.dataformat.univocity.UniVocityTestHelper.join;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This class tests the unmarshalling of {@link org.apache.camel.dataformat.univocity.UniVocityTsvDataFormat}.
@@ -111,12 +111,7 @@ public final class UniVocityTsvDataFormatUnmarshalTest extends CamelTestSupport
         assertEquals(Arrays.asList("A", "B", "C"), body.next());
 
         // Try to remove the element
-        try {
-            body.remove();
-            fail("Should have thrown a UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            // Success
-        }
+        assertThrows(UnsupportedOperationException.class, body::remove);
 
         // Read all the lines
         assertTrue(body.hasNext());
@@ -126,12 +121,7 @@ public final class UniVocityTsvDataFormatUnmarshalTest extends CamelTestSupport
         assertFalse(body.hasNext());
 
         // Try to read one more element
-        try {
-            body.next();
-            fail("Should have thrown a NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Success
-        }
+        assertThrows(NoSuchElementException.class, body::next);
     }
 
     /**


(camel) 20/36: CAMEL-21196: modernize exception-based assertions in camel-fhir

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 7387164ff3ba391de0cff92be7ceae3cd32758ef
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:21:36 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-fhir
    
    Replace try-catch-fail patterns with assertThrows in:
    - FhirJsonDataformatErrorHandlerTest
    - FhirXmlDataformatErrorHandlerTest
    - FhirJsonDataformatErrorHandlerSpringTest
    - FhirXmlDataformatErrorHandlerSpringTest
---
 .../fhir/dataformat/FhirJsonDataformatErrorHandlerTest.java  | 12 +++++-------
 .../fhir/dataformat/FhirXmlDataformatErrorHandlerTest.java   | 12 +++++-------
 .../spring/FhirJsonDataformatErrorHandlerSpringTest.java     | 12 +++++-------
 .../spring/FhirXmlDataformatErrorHandlerSpringTest.java      | 12 +++++-------
 4 files changed, 20 insertions(+), 28 deletions(-)

diff --git a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirJsonDataformatErrorHandlerTest.java b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirJsonDataformatErrorHandlerTest.java
index 6518be89c72c..f40488aef9f2 100644
--- a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirJsonDataformatErrorHandlerTest.java
+++ b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirJsonDataformatErrorHandlerTest.java
@@ -32,8 +32,8 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class FhirJsonDataformatErrorHandlerTest extends CamelTestSupport {
 
@@ -50,12 +50,10 @@ public class FhirJsonDataformatErrorHandlerTest extends CamelTestSupport {
 
     @Test
     public void unmarshalParserErrorHandler() {
-        try {
-            template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT);
-            fail("Expected a DataFormatException");
-        } catch (CamelExecutionException e) {
-            assertTrue(e.getCause() instanceof DataFormatException);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT),
+                "Expected a DataFormatException");
+        assertTrue(e.getCause() instanceof DataFormatException);
     }
 
     @Test
diff --git a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirXmlDataformatErrorHandlerTest.java b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirXmlDataformatErrorHandlerTest.java
index c98e3dc50839..16d9c6779bb0 100644
--- a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirXmlDataformatErrorHandlerTest.java
+++ b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirXmlDataformatErrorHandlerTest.java
@@ -30,8 +30,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.hl7.fhir.r4.model.Patient;
 import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class FhirXmlDataformatErrorHandlerTest extends CamelTestSupport {
 
@@ -47,12 +47,10 @@ public class FhirXmlDataformatErrorHandlerTest extends CamelTestSupport {
 
     @Test
     public void unmarshalParserErrorHandler() {
-        try {
-            template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT);
-            fail("Expected a DataFormatException");
-        } catch (CamelExecutionException e) {
-            assertTrue(e.getCause() instanceof DataFormatException);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT),
+                "Expected a DataFormatException");
+        assertTrue(e.getCause() instanceof DataFormatException);
     }
 
     @Test
diff --git a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirJsonDataformatErrorHandlerSpringTest.java b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirJsonDataformatErrorHandlerSpringTest.java
index 2e4d16ace959..493db90c55f0 100644
--- a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirJsonDataformatErrorHandlerSpringTest.java
+++ b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirJsonDataformatErrorHandlerSpringTest.java
@@ -28,8 +28,8 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class FhirJsonDataformatErrorHandlerSpringTest extends CamelSpringTestSupport {
 
@@ -44,12 +44,10 @@ public class FhirJsonDataformatErrorHandlerSpringTest extends CamelSpringTestSup
 
     @Test
     public void unmarshalParserErrorHandler() {
-        try {
-            template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT);
-            fail("Expected a DataFormatException");
-        } catch (CamelExecutionException e) {
-            assertTrue(e.getCause() instanceof DataFormatException);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT),
+                "Expected a DataFormatException");
+        assertTrue(e.getCause() instanceof DataFormatException);
     }
 
     @Test
diff --git a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirXmlDataformatErrorHandlerSpringTest.java b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirXmlDataformatErrorHandlerSpringTest.java
index 4ecde56bbcca..9195c4e646a5 100644
--- a/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirXmlDataformatErrorHandlerSpringTest.java
+++ b/components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirXmlDataformatErrorHandlerSpringTest.java
@@ -26,8 +26,8 @@ import org.junit.jupiter.api.Test;
 import org.springframework.context.support.AbstractApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class FhirXmlDataformatErrorHandlerSpringTest extends CamelSpringTestSupport {
 
@@ -42,12 +42,10 @@ public class FhirXmlDataformatErrorHandlerSpringTest extends CamelSpringTestSupp
 
     @Test
     public void unmarshalParserErrorHandler() {
-        try {
-            template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT);
-            fail("Expected a DataFormatException");
-        } catch (CamelExecutionException e) {
-            assertTrue(e.getCause() instanceof DataFormatException);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT),
+                "Expected a DataFormatException");
+        assertTrue(e.getCause() instanceof DataFormatException);
     }
 
     @Test


(camel) 10/36: CAMEL-21196: modernize exception-based assertions in camel-keycloak

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 8e28eda0b1dca1ac9700103bf2cefbee6af83ec4
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:41:40 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-keycloak
---
 .../security/KeycloakSecurityHelperTest.java       | 22 ++++++---------
 .../TransactionalClientDataSourceAsyncTest.java    | 16 +++++------
 ...sactionalClientDataSourceNotTransactedTest.java | 14 ++++------
 .../TransactionalClientDataSourceTest.java         | 16 +++++------
 ...ourceWithOnExceptionHandledAndRollbackTest.java |  9 ++----
 ...lientDataSourceWithOnExceptionRollbackTest.java | 16 +++++------
 ...ctionalClientDataSourceWithOnExceptionTest.java | 16 +++++------
 .../TransactionalClientWithRollbackTest.java       | 12 ++++----
 .../SpringCamelContextStartingFailedEventTest.java | 18 ++++++------
 .../spring/processor/SpringFilterNoChildTest.java  | 18 ++++++------
 .../processor/SpringTryCatchMisconfiguredTest.java | 32 ++++++++++------------
 11 files changed, 83 insertions(+), 106 deletions(-)

diff --git a/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityHelperTest.java b/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityHelperTest.java
index b17823f18179..2cbdc9ae61ba 100644
--- a/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityHelperTest.java
+++ b/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityHelperTest.java
@@ -132,23 +132,19 @@ public class KeycloakSecurityHelperTest {
     }
 
     @Test
-    void testParseAndVerifyAccessTokenWithInvalidToken() {
+    void testParseAndVerifyAccessTokenWithInvalidToken() throws Exception {
         // Test that verification fails with invalid token
         String invalidToken = "invalid.jwt.token";
         String expectedIssuer = "http://localhost:8080/realms/test";
 
-        try {
-            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
-            keyGen.initialize(2048);
-            KeyPair keyPair = keyGen.generateKeyPair();
-            PublicKey publicKey = keyPair.getPublic();
-
-            assertThrows(VerificationException.class, () -> {
-                KeycloakSecurityHelper.parseAndVerifyAccessToken(invalidToken, publicKey, expectedIssuer);
-            });
-        } catch (Exception e) {
-            fail("Failed to generate test keys: " + e.getMessage());
-        }
+        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
+        keyGen.initialize(2048);
+        KeyPair keyPair = keyGen.generateKeyPair();
+        PublicKey publicKey = keyPair.getPublic();
+
+        assertThrows(VerificationException.class, () -> {
+            KeycloakSecurityHelper.parseAndVerifyAccessToken(invalidToken, publicKey, expectedIssuer);
+        });
     }
 
     @Test
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java
index c83fb5f41e0c..caf0de4f4fad 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java
@@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
@@ -39,15 +39,13 @@ public class TransactionalClientDataSourceAsyncTest extends TransactionalClientD
         MockEndpoint mock = getMockEndpoint("mock:error");
         mock.expectedMessageCount(1);
 
-        try {
+        RuntimeCamelException e = assertThrows(RuntimeCamelException.class, () -> {
             template.sendBody("direct:fail", "Hello World");
-            fail("Should have thrown exception");
-        } catch (RuntimeCamelException e) {
-            // expected as we fail
-            assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
-            assertTrue(e.getCause().getCause() instanceof IllegalArgumentException);
-            assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage());
-        }
+        });
+        // expected as we fail
+        assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
+        assertTrue(e.getCause().getCause() instanceof IllegalArgumentException);
+        assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage());
 
         assertMockEndpointsSatisfied();
 
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java
index 38842e1ea4b1..f50acc8d087c 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java
@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Same route but not transacted
@@ -33,14 +33,12 @@ public class TransactionalClientDataSourceNotTransactedTest extends Transactiona
     @Override
     @Test
     public void testTransactionRollback() throws Exception {
-        try {
+        RuntimeCamelException e = assertThrows(RuntimeCamelException.class, () -> {
             template.sendBody("direct:fail", "Hello World");
-            fail("Should have thrown exception");
-        } catch (RuntimeCamelException e) {
-            // expected as we fail
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-            assertEquals("We don't have Donkeys, only Camels", e.getCause().getMessage());
-        }
+        });
+        // expected as we fail
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
+        assertEquals("We don't have Donkeys, only Camels", e.getCause().getMessage());
 
         int count = jdbc.queryForObject("select count(*) from books", Integer.class);
         // should get 2 books as the first operation will succeed and we are not transacted
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java
index 8acdfd9aff69..adc7cfae1825 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
@@ -44,15 +44,13 @@ public class TransactionalClientDataSourceTest extends TransactionClientDataSour
     // START SNIPPET: e4
     @Test
     public void testTransactionRollback() throws Exception {
-        try {
+        RuntimeCamelException e = assertThrows(RuntimeCamelException.class, () -> {
             template.sendBody("direct:fail", "Hello World");
-            fail("Should have thrown exception");
-        } catch (RuntimeCamelException e) {
-            // expected as we fail
-            assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
-            assertTrue(e.getCause().getCause() instanceof IllegalArgumentException);
-            assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage());
-        }
+        });
+        // expected as we fail
+        assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
+        assertTrue(e.getCause().getCause() instanceof IllegalArgumentException);
+        assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage());
 
         int count = jdbc.queryForObject("select count(*) from books", Integer.class);
         assertEquals(1, count, "Number of books");
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionHandledAndRollbackTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionHandledAndRollbackTest.java
index 9ff113281566..80494d3e1c28 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionHandledAndRollbackTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionHandledAndRollbackTest.java
@@ -24,7 +24,7 @@ import org.apache.camel.spring.spi.SpringTransactionPolicy;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
@@ -37,12 +37,9 @@ public class TransactionalClientDataSourceWithOnExceptionHandledAndRollbackTest
         MockEndpoint mock = getMockEndpoint("mock:error");
         mock.expectedMessageCount(1);
 
-        try {
+        assertThrows(CamelExecutionException.class, () -> {
             template.requestBody("direct:fail", "Hello World", String.class);
-            fail("Should have thrown exception");
-        } catch (CamelExecutionException e) {
-            // expected
-        }
+        });
 
         assertMockEndpointsSatisfied();
 
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionRollbackTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionRollbackTest.java
index 07eb460e8e8b..eaf9302e4643 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionRollbackTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionRollbackTest.java
@@ -25,7 +25,7 @@ import org.apache.camel.spring.spi.SpringTransactionPolicy;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
@@ -38,15 +38,13 @@ public class TransactionalClientDataSourceWithOnExceptionRollbackTest extends Tr
         MockEndpoint mock = getMockEndpoint("mock:error");
         mock.expectedMessageCount(1);
 
-        try {
+        RuntimeCamelException e = assertThrows(RuntimeCamelException.class, () -> {
             template.sendBody("direct:fail", "Hello World");
-            fail("Should have thrown exception");
-        } catch (RuntimeCamelException e) {
-            // expected as we fail
-            assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
-            RollbackExchangeException rollback = assertIsInstanceOf(RollbackExchangeException.class, e.getCause().getCause());
-            assertEquals("Donkey in Action", rollback.getExchange().getIn().getBody());
-        }
+        });
+        // expected as we fail
+        assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
+        RollbackExchangeException rollback = assertIsInstanceOf(RollbackExchangeException.class, e.getCause().getCause());
+        assertEquals("Donkey in Action", rollback.getExchange().getIn().getBody());
 
         assertMockEndpointsSatisfied();
 
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java
index eda42ba0f5fa..93fa621b010a 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
@@ -38,15 +38,13 @@ public class TransactionalClientDataSourceWithOnExceptionTest extends Transactio
         MockEndpoint mock = getMockEndpoint("mock:error");
         mock.expectedMessageCount(1);
 
-        try {
+        RuntimeCamelException e = assertThrows(RuntimeCamelException.class, () -> {
             template.sendBody("direct:fail", "Hello World");
-            fail("Should have thrown exception");
-        } catch (RuntimeCamelException e) {
-            // expected as we fail
-            assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
-            assertTrue(e.getCause().getCause() instanceof IllegalArgumentException);
-            assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage());
-        }
+        });
+        // expected as we fail
+        assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
+        assertTrue(e.getCause().getCause() instanceof IllegalArgumentException);
+        assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage());
 
         assertMockEndpointsSatisfied();
 
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java
index 36e978694835..72af2771fc18 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java
@@ -32,7 +32,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Transactional client test with rollback in the DSL.
@@ -66,13 +66,11 @@ public class TransactionalClientWithRollbackTest extends SpringTestSupport {
 
     @Test
     public void testTransactionRollback() throws Exception {
-        try {
+        RuntimeCamelException e = assertThrows(RuntimeCamelException.class, () -> {
             template.sendBody("direct:fail", "Hello World");
-            fail("Should have thrown a RollbackExchangeException");
-        } catch (RuntimeCamelException e) {
-            assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
-            assertTrue(e.getCause().getCause() instanceof RollbackExchangeException);
-        }
+        });
+        assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
+        assertTrue(e.getCause().getCause() instanceof RollbackExchangeException);
 
         int count = jdbc.queryForObject("select count(*) from books", Integer.class);
         assertEquals(1, count, "Number of books");
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java
index 3fee75a8a96c..2bbf66b5d289 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java
@@ -26,7 +26,7 @@ import org.springframework.context.support.AbstractXmlApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 @DisabledOnOs(OS.AIX)
 public class SpringCamelContextStartingFailedEventTest extends SpringTestSupport {
@@ -38,14 +38,14 @@ public class SpringCamelContextStartingFailedEventTest extends SpringTestSupport
 
     @Override
     protected AbstractXmlApplicationContext createApplicationContext() {
-        try (ClassPathXmlApplicationContext x = new ClassPathXmlApplicationContext(
-                "org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.xml")) {
-            fail("Should thrown an exception");
-        } catch (Exception e) {
-            FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e);
-            assertIsInstanceOf(NoSuchEndpointException.class, ftcre.getCause());
-            // expected
-        }
+        Exception e = assertThrows(Exception.class, () -> {
+            try (ClassPathXmlApplicationContext x = new ClassPathXmlApplicationContext(
+                    "org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.xml")) {
+            }
+        });
+        FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e);
+        assertIsInstanceOf(NoSuchEndpointException.class, ftcre.getCause());
+        // expected
 
         // fallback to load another file that works
         return new ClassPathXmlApplicationContext("/org/apache/camel/spring/disableJmxConfig.xml");
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java
index 03a9a8d8e494..fdee058d2c9a 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java
@@ -25,20 +25,20 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class SpringFilterNoChildTest extends SpringTestSupport {
 
     @Override
     protected AbstractXmlApplicationContext createApplicationContext() {
-        try (ClassPathXmlApplicationContext x
-                = new ClassPathXmlApplicationContext("org/apache/camel/spring/processor/filterNoChild.xml")) {
-            fail("Should thrown an exception");
-        } catch (Exception e) {
-            FailedToCreateRouteException cause = assertIsInstanceOf(FailedToCreateRouteException.class, e);
-            IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, cause.getCause());
-            assertEquals("Definition has no children on Filter[xpath{$foo = 'bar'} -> []]", iae.getMessage());
-        }
+        Exception e = assertThrows(Exception.class, () -> {
+            try (ClassPathXmlApplicationContext x
+                    = new ClassPathXmlApplicationContext("org/apache/camel/spring/processor/filterNoChild.xml")) {
+            }
+        });
+        FailedToCreateRouteException cause = assertIsInstanceOf(FailedToCreateRouteException.class, e);
+        IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, cause.getCause());
+        assertEquals("Definition has no children on Filter[xpath{$foo = 'bar'} -> []]", iae.getMessage());
         return null;
     }
 
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringTryCatchMisconfiguredTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringTryCatchMisconfiguredTest.java
index 17e47e304f00..286994d5943a 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringTryCatchMisconfiguredTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringTryCatchMisconfiguredTest.java
@@ -23,31 +23,27 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class SpringTryCatchMisconfiguredTest extends ContextTestSupport {
 
     @Override
     protected CamelContext createCamelContext() throws Exception {
-        try {
+        Exception e1 = assertThrows(Exception.class, () -> {
             createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringTryCatchMisconfiguredTest.xml");
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            FailedToCreateRouteException ftce = assertIsInstanceOf(FailedToCreateRouteException.class, e);
-            IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, ftce.getCause());
-            assertEquals(
-                    "This doCatch should have a doTry as its parent on DoCatch[ [class java.io.IOException] -> [to[mock:fail]]]",
-                    iae.getMessage());
-        }
-
-        try {
+        });
+        FailedToCreateRouteException ftce = assertIsInstanceOf(FailedToCreateRouteException.class, e1);
+        IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, ftce.getCause());
+        assertEquals(
+                "This doCatch should have a doTry as its parent on DoCatch[ [class java.io.IOException] -> [to[mock:fail]]]",
+                iae.getMessage());
+
+        Exception e2 = assertThrows(Exception.class, () -> {
             createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringTryCatchMisconfiguredFinallyTest.xml");
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e);
-            IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, ftcre.getCause());
-            assertEquals("This doFinally should have a doTry as its parent on DoFinally[[to[mock:finally]]]", iae.getMessage());
-        }
+        });
+        FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e2);
+        IllegalArgumentException iae2 = assertIsInstanceOf(IllegalArgumentException.class, ftcre.getCause());
+        assertEquals("This doFinally should have a doTry as its parent on DoFinally[[to[mock:finally]]]", iae2.getMessage());
 
         // return a working context instead, to let this test pass
         return createSpringCamelContext(this, "org/apache/camel/spring/processor/convertBody.xml");


(camel) 21/36: CAMEL-21196: modernize exception-based assertions in camel-dns

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 83996de6c3270ca018713cc1064b8f52c17ae25c
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:37:04 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-dns
---
 .../camel/component/dns/DnsIpEndpointSpringTest.java   | 18 +++++++-----------
 .../apache/camel/component/dns/DnsIpEndpointTest.java  | 18 +++++++-----------
 .../camel/component/dns/DnsIpHeaderTransferTest.java   | 18 +++++++-----------
 .../component/dns/DnsLookupEndpointSpringTest.java     | 18 +++++++-----------
 .../camel/component/dns/DnsLookupEndpointTest.java     | 18 +++++++-----------
 5 files changed, 35 insertions(+), 55 deletions(-)

diff --git a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointSpringTest.java b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointSpringTest.java
index 93f88f62f17f..e526b243bc1e 100644
--- a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointSpringTest.java
+++ b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointSpringTest.java
@@ -26,8 +26,8 @@ import org.junit.jupiter.api.Test;
 import org.springframework.context.support.AbstractApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * A series of tests to check the IP lookup operation.
@@ -43,24 +43,20 @@ public class DnsIpEndpointSpringTest extends CamelSpringTestSupport {
     @Test
     void testNullIPRequests() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.domain", null);
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
     @Test
     void testEmptyIPRequests() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.domain", "");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
diff --git a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointTest.java b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointTest.java
index 91a2c0eba20b..41be3b617ab9 100644
--- a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointTest.java
+++ b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpEndpointTest.java
@@ -25,8 +25,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Disabled;
 import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * A series of tests to check the IP lookup operation.
@@ -52,24 +52,20 @@ public class DnsIpEndpointTest extends CamelTestSupport {
     @Test
     void testNullIPRequests() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.domain", null);
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
     @Test
     void testEmptyIPRequests() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.domain", "");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
diff --git a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpHeaderTransferTest.java b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpHeaderTransferTest.java
index da712b107db6..cdaa093ed821 100644
--- a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpHeaderTransferTest.java
+++ b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsIpHeaderTransferTest.java
@@ -25,8 +25,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Disabled;
 import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class DnsIpHeaderTransferTest extends CamelTestSupport {
 
@@ -50,12 +50,10 @@ public class DnsIpHeaderTransferTest extends CamelTestSupport {
     void testNullIPRequests() throws Exception {
         resultEndpoint.expectedMessageCount(0);
 
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.domain", null);
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
@@ -63,12 +61,10 @@ public class DnsIpHeaderTransferTest extends CamelTestSupport {
     void testEmptyIPRequests() throws Exception {
         resultEndpoint.expectedMessageCount(0);
 
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.domain", "");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
diff --git a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointSpringTest.java b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointSpringTest.java
index 8e88cab02d97..715825753a48 100644
--- a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointSpringTest.java
+++ b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointSpringTest.java
@@ -32,8 +32,8 @@ import org.springframework.context.support.AbstractApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 import org.xbill.DNS.Record;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * A set of test cases to make DNS lookups.
@@ -49,24 +49,20 @@ public class DnsLookupEndpointSpringTest extends CamelSpringTestSupport {
     @Test
     void testDNSWithNoHeaders() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBody("hello");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
     @Test
     void testDNSWithEmptyNameHeader() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.name", "");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException, t.toString());
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException, e.toString());
         resultEndpoint.assertIsSatisfied();
     }
 
diff --git a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointTest.java b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointTest.java
index fd21dae42797..500a8e0e0b15 100644
--- a/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointTest.java
+++ b/components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsLookupEndpointTest.java
@@ -31,8 +31,8 @@ import org.junit.jupiter.api.Disabled;
 import org.junit.jupiter.api.Test;
 import org.xbill.DNS.Record;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * A set of test cases to make DNS lookups.
@@ -58,24 +58,20 @@ public class DnsLookupEndpointTest extends CamelTestSupport {
     @Test
     void testDNSWithNoHeaders() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBody("hello");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException);
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
         resultEndpoint.assertIsSatisfied();
     }
 
     @Test
     void testDNSWithEmptyNameHeader() throws Exception {
         resultEndpoint.expectedMessageCount(0);
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("hello", "dns.name", "");
-            fail("Should have thrown exception");
-        } catch (Exception t) {
-            assertTrue(t.getCause() instanceof IllegalArgumentException, t.toString());
-        }
+        });
+        assertTrue(e.getCause() instanceof IllegalArgumentException, e.toString());
         resultEndpoint.assertIsSatisfied();
     }
 


(camel) 34/36: CAMEL-21196: modernize exception-based assertions in camel-thrift

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 5a4350f455043addc09ca26969dbe234a370a885
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:49:13 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-thrift
    
    Replace try-catch-fail patterns with assertThrows in test classes to use
    modern JUnit 5 exception testing approach, improving code clarity and consistency.
---
 .../thrift/ThriftProducerSecurityTest.java          | 13 +++++--------
 .../component/thrift/ThriftProducerSyncTest.java    | 13 +++++--------
 .../thrift/ThriftMarshalAndUnmarshalSpringTest.java | 21 +++++++++------------
 .../thrift/ThriftMarshalAndUnmarshalTest.java       | 21 +++++++++------------
 4 files changed, 28 insertions(+), 40 deletions(-)

diff --git a/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSecurityTest.java b/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSecurityTest.java
index c0da4a6b2afc..8c7999c06fba 100644
--- a/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSecurityTest.java
+++ b/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSecurityTest.java
@@ -49,8 +49,8 @@ import org.slf4j.LoggerFactory;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class ThriftProducerSecurityTest extends CamelTestSupport {
     private static final Logger LOG = LoggerFactory.getLogger(ThriftProducerSecurityTest.class);
@@ -144,13 +144,10 @@ public class ThriftProducerSecurityTest extends CamelTestSupport {
         requestBody.add(1);
         requestBody.add(new Work(THRIFT_TEST_NUM1, 0, Operation.DIVIDE));
 
-        try {
-            template.requestBody("direct:thrift-secured-calculate", requestBody);
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            assertTrue(ex instanceof CamelExecutionException, "Expect CamelExecutionException");
-            assertTrue(ex.getCause() instanceof InvalidOperation, "Get an InvalidOperation exception");
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> template.requestBody("direct:thrift-secured-calculate", requestBody));
+        assertTrue(ex instanceof CamelExecutionException, "Expect CamelExecutionException");
+        assertTrue(ex.getCause() instanceof InvalidOperation, "Get an InvalidOperation exception");
     }
 
     @Test
diff --git a/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSyncTest.java b/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSyncTest.java
index de826db56017..f05e5727b667 100644
--- a/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSyncTest.java
+++ b/components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerSyncTest.java
@@ -34,8 +34,8 @@ import org.slf4j.LoggerFactory;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class ThriftProducerSyncTest extends ThriftProducerBaseTest {
     private static final Logger LOG = LoggerFactory.getLogger(ThriftProducerSyncTest.class);
@@ -84,13 +84,10 @@ public class ThriftProducerSyncTest extends ThriftProducerBaseTest {
         requestBody.add(1);
         requestBody.add(new Work(THRIFT_TEST_NUM1, 0, Operation.DIVIDE));
 
-        try {
-            template.requestBody("direct:thrift-calculate", requestBody);
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            assertTrue(ex instanceof CamelExecutionException, "Expect CamelExecutionException");
-            assertTrue(ex.getCause() instanceof InvalidOperation, "Get an InvalidOperation exception");
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> template.requestBody("direct:thrift-calculate", requestBody));
+        assertTrue(ex instanceof CamelExecutionException, "Expect CamelExecutionException");
+        assertTrue(ex.getCause() instanceof InvalidOperation, "Get an InvalidOperation exception");
     }
 
     @Test
diff --git a/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalSpringTest.java b/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalSpringTest.java
index c8f7ddd0d2d7..cf8b6ca02c78 100644
--- a/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalSpringTest.java
+++ b/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalSpringTest.java
@@ -27,8 +27,8 @@ import org.junit.jupiter.api.Test;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class ThriftMarshalAndUnmarshalSpringTest extends CamelSpringTestSupport {
     private static final String WORK_TEST_COMMENT = "This is a test thrift data";
@@ -58,17 +58,14 @@ public class ThriftMarshalAndUnmarshalSpringTest extends CamelSpringTestSupport
 
     @Test
     public void testMarshalAndUnmarshalWithDSL3() {
-        try {
-            context.addRoutes(new RouteBuilder() {
-                @Override
-                public void configure() {
-                    from("direct:unmarshalC").unmarshal().thrift(new CamelException("wrong instance")).to("mock:reverse");
-                }
-            });
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> context.addRoutes(new RouteBuilder() {
+                    @Override
+                    public void configure() {
+                        from("direct:unmarshalC").unmarshal().thrift(new CamelException("wrong instance")).to("mock:reverse");
+                    }
+                }));
+        assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
     }
 
     private void marshalAndUnmarshal(String inURI, String outURI) throws Exception {
diff --git a/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalTest.java b/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalTest.java
index 33da0d854b50..ce96c9daebd3 100644
--- a/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalTest.java
+++ b/components/camel-thrift/src/test/java/org/apache/camel/dataformat/thrift/ThriftMarshalAndUnmarshalTest.java
@@ -26,8 +26,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class ThriftMarshalAndUnmarshalTest extends CamelTestSupport {
     private static final String WORK_TEST_COMMENT = "This is a test thrift data";
@@ -52,17 +52,14 @@ public class ThriftMarshalAndUnmarshalTest extends CamelTestSupport {
 
     @Test
     public void testMarshalAndUnmarshalWithDSL3() {
-        try {
-            context.addRoutes(new RouteBuilder() {
-                @Override
-                public void configure() {
-                    from("direct:unmarshalC").unmarshal().thrift(new CamelException("wrong instance")).to("mock:reverse");
-                }
-            });
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> context.addRoutes(new RouteBuilder() {
+                    @Override
+                    public void configure() {
+                        from("direct:unmarshalC").unmarshal().thrift(new CamelException("wrong instance")).to("mock:reverse");
+                    }
+                }));
+        assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
     }
 
     private void marshalAndUnmarshal(String inURI, String outURI) throws Exception {


(camel) 05/36: CAMEL-21196: modernize exception-based assertions in camel-crypto

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit f14d1151a3375b3565e70f1b1b86c955f4bdda5c
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:21:44 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-crypto
    
    Convert try-catch-fail patterns to JUnit 5 assertThrows in CryptoDataFormatTest.
    Replaced legacy fail() with assertThrows() for cleaner and more idiomatic exception testing.
---
 .../apache/camel/converter/crypto/CryptoDataFormatTest.java  | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/components/camel-crypto/src/test/java/org/apache/camel/converter/crypto/CryptoDataFormatTest.java b/components/camel-crypto/src/test/java/org/apache/camel/converter/crypto/CryptoDataFormatTest.java
index cb738b783e24..2e91db904324 100644
--- a/components/camel-crypto/src/test/java/org/apache/camel/converter/crypto/CryptoDataFormatTest.java
+++ b/components/camel-crypto/src/test/java/org/apache/camel/converter/crypto/CryptoDataFormatTest.java
@@ -40,8 +40,8 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class CryptoDataFormatTest extends CamelTestSupport {
 
@@ -131,12 +131,10 @@ public class CryptoDataFormatTest extends CamelTestSupport {
 
     @Test
     void testNoAlgorithm() throws Exception {
-        try {
-            doRoundTripEncryptionTests("direct:no-algorithm");
-            fail("Failure expected on no algorithm specified");
-        } catch (CamelExecutionException ex) {
-            assertTrue(ex.getCause() instanceof NoSuchAlgorithmException);
-        }
+        CamelExecutionException ex = assertThrows(CamelExecutionException.class,
+                () -> doRoundTripEncryptionTests("direct:no-algorithm"),
+                "Failure expected on no algorithm specified");
+        assertTrue(ex.getCause() instanceof NoSuchAlgorithmException);
     }
 
     private void validateHeaderIsCleared(Exchange ex) {


(camel) 17/36: CAMEL-21196: modernize exception-based assertions in camel-jaxb

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 2f96d33ea08f11f7674916181738a6a97978850f
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:21:26 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jaxb
    
    Replace try-catch-fail patterns with assertThrows in:
    - JaxbDataFormatMustBeJAXBElementTest
    - CamelJaxbFallbackConverterTest
    - NonXmlCharFiltererTest
---
 .../camel/jaxb/CamelJaxbFallbackConverterTest.java | 31 ++++++++--------------
 .../jaxb/JaxbDataFormatMustBeJAXBElementTest.java  | 16 +++++------
 2 files changed, 18 insertions(+), 29 deletions(-)

diff --git a/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/CamelJaxbFallbackConverterTest.java b/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/CamelJaxbFallbackConverterTest.java
index f3cb6624d6f4..ccb2c49c2dde 100644
--- a/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/CamelJaxbFallbackConverterTest.java
+++ b/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/CamelJaxbFallbackConverterTest.java
@@ -31,8 +31,8 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class CamelJaxbFallbackConverterTest extends ExchangeTestSupport {
 
@@ -62,19 +62,13 @@ public class CamelJaxbFallbackConverterTest extends ExchangeTestSupport {
     public void testFallbackConverterUnmarshalWithNonJAXBComplaintValue() {
         TypeConverter converter = context.getTypeConverter();
 
-        try {
-            converter.convertTo(Foo.class, "Not every String is XML");
-            fail("Should have thrown exception");
-        } catch (TypeConversionException e) {
-            // expected
-        }
-
-        try {
-            converter.convertTo(Bar.class, "<bar></bar");
-            fail("Should have thrown exception");
-        } catch (TypeConversionException e) {
-            // expected
-        }
+        assertThrows(TypeConversionException.class,
+                () -> converter.convertTo(Foo.class, "Not every String is XML"),
+                "Should have thrown exception");
+
+        assertThrows(TypeConversionException.class,
+                () -> converter.convertTo(Bar.class, "<bar></bar"),
+                "Should have thrown exception");
     }
 
     @Test
@@ -93,12 +87,9 @@ public class CamelJaxbFallbackConverterTest extends ExchangeTestSupport {
 
         byte[] buffers = "<Person><firstName>FOO</firstName><lastName>BAR\u0008</lastName></Person>".getBytes("UTF-8");
         InputStream is = new ByteArrayInputStream(buffers);
-        try {
-            converter.convertTo(PersonType.class, exchange, is);
-            fail("Should have thrown exception");
-        } catch (TypeConversionException e) {
-            // expected
-        }
+        assertThrows(TypeConversionException.class,
+                () -> converter.convertTo(PersonType.class, exchange, is),
+                "Should have thrown exception");
     }
 
     @Test
diff --git a/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java b/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java
index d8185656d8cd..a4499084d9be 100644
--- a/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java
+++ b/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java
@@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class JaxbDataFormatMustBeJAXBElementTest extends CamelTestSupport {
 
@@ -50,14 +50,12 @@ public class JaxbDataFormatMustBeJAXBElementTest extends CamelTestSupport {
     public void testJaxbMarshalling2() throws InterruptedException {
         getMockEndpoint("mock:result").expectedMessageCount(0);
 
-        try {
-            template.sendBody("direct:start2", "<foo><bar>Hello Bar</bar></foo>");
-            fail("Should have thrown exception");
-        } catch (CamelExecutionException e) {
-            InvalidPayloadException ipe = assertIsInstanceOf(InvalidPayloadException.class, e.getCause().getCause());
-            assertNotNull(ipe);
-            assertEquals(JAXBElement.class, ipe.getType());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody("direct:start2", "<foo><bar>Hello Bar</bar></foo>"),
+                "Should have thrown exception");
+        InvalidPayloadException ipe = assertIsInstanceOf(InvalidPayloadException.class, e.getCause().getCause());
+        assertNotNull(ipe);
+        assertEquals(JAXBElement.class, ipe.getType());
 
         MockEndpoint.assertIsSatisfied(context);
     }


(camel) 13/36: CAMEL-21196: modernize exception-based assertions in camel-platform-http-vertx

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit dfa0835ae888f7d89d7e5484e35c4248925932e0
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:44:06 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-platform-http-vertx
---
 .../platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java  | 1 -
 .../platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java         | 1 -
 2 files changed, 2 deletions(-)

diff --git a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java
index c02c22a3b53b..a242fca8ed36 100644
--- a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java
+++ b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java
@@ -28,7 +28,6 @@ import static io.restassured.RestAssured.given;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.equalToCompressingWhiteSpace;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class PlatformHttpRestOpenApiConsumerRestDslTest {
 
diff --git a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java
index fe8276b81a45..8bf85c8d23a1 100644
--- a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java
+++ b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java
@@ -25,7 +25,6 @@ import org.junit.jupiter.api.Test;
 import static io.restassured.RestAssured.given;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.equalToCompressingWhiteSpace;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class PlatformHttpRestOpenApiConsumerTest {
 


(camel) 28/36: CAMEL-21196: modernize exception-based assertions in camel-undertow

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit c197fbc53422e69006ddfa9397c8a28eea0d0cd6
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:46:24 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-undertow
    
    Replace try-catch-fail patterns with assertThrows in all test files.
    Modernizes exception handling assertions to use JUnit 5 best practices.
    
    Files changed:
    - SecurityProviderHttpHandlerTest.java
    - SecurityProviderNoAcceptanceTest.java
    - SecurityProviderRolesFromComponentTest.java
    - SecurityProviderTest.java
    - SecurityProviderWithoutProviderTest.java
    - RestUndertowMethodNotAllowedTest.java
    - RestUndertowHttpBindingModeXmlTest.java
    - UndertowSuspendResumeTest.java
    - UndertowError500Test.java
    - UndertowHandlersSpringTest.java
    - UndertowHttp2Test.java
    - UndertowPrefixMatchingTest.java
    - DefaultUndertowHttpBindingTest.java
    - UndertowConsumerUnregisterTest.java
---
 .../undertow/DefaultUndertowHttpBindingTest.java   |  3 +--
 .../undertow/UndertowConsumerUnregisterTest.java   | 13 +++++-------
 .../component/undertow/UndertowError500Test.java   | 10 +++------
 .../undertow/UndertowHandlersSpringTest.java       | 17 +++++----------
 .../component/undertow/UndertowHttp2Test.java      | 14 ++++---------
 .../undertow/UndertowPrefixMatchingTest.java       | 13 +++++-------
 .../undertow/UndertowSuspendResumeTest.java        | 12 ++++-------
 .../rest/RestUndertowHttpBindingModeXmlTest.java   |  9 ++------
 .../rest/RestUndertowMethodNotAllowedTest.java     | 24 ++++++++--------------
 .../spi/SecurityProviderHttpHandlerTest.java       | 15 +++++---------
 .../spi/SecurityProviderNoAcceptanceTest.java      | 15 +++++---------
 .../SecurityProviderRolesFromComponentTest.java    | 15 +++++---------
 .../undertow/spi/SecurityProviderTest.java         | 15 +++++---------
 .../spi/SecurityProviderWithoutProviderTest.java   | 15 +++++---------
 14 files changed, 63 insertions(+), 127 deletions(-)

diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/DefaultUndertowHttpBindingTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/DefaultUndertowHttpBindingTest.java
index 3e19e1a13087..5171562f576b 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/DefaultUndertowHttpBindingTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/DefaultUndertowHttpBindingTest.java
@@ -31,7 +31,6 @@ import org.xnio.channels.EmptyStreamSourceChannel;
 import org.xnio.channels.StreamSourceChannel;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class DefaultUndertowHttpBindingTest {
 
@@ -100,7 +99,7 @@ public class DefaultUndertowHttpBindingTest {
             @Override
             public int read(ByteBuffer dst) {
                 if (mustWait) {
-                    fail("must wait before reading");
+                    throw new AssertionError("must wait before reading");
                 }
                 if (chunk < delayedPayloads.length) {
                     byte[] delayedPayload = delayedPayloads[chunk].getBytes();
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowConsumerUnregisterTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowConsumerUnregisterTest.java
index d36f66353f58..2033d7b27225 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowConsumerUnregisterTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowConsumerUnregisterTest.java
@@ -26,8 +26,8 @@ import org.apache.camel.component.mock.MockEndpoint;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class UndertowConsumerUnregisterTest extends BaseUndertowTest {
 
@@ -42,13 +42,10 @@ public class UndertowConsumerUnregisterTest extends BaseUndertowTest {
         component.unregisterEndpoint(consumerBar, consumerBar.getEndpoint().getHttpHandlerRegistrationInfo(),
                 consumerBar.getEndpoint().getSslContext());
 
-        try {
-            template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
-            fail("Expected exception when connecting to undertow endpoint");
-        } catch (CamelExecutionException e) {
-            // Expected because unregistering all consumers should shut down the Undertow server
-            assertTrue(e.getExchange().getException() instanceof ConnectException);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class));
+        // Expected because unregistering all consumers should shut down the Undertow server
+        assertTrue(e.getExchange().getException() instanceof ConnectException);
     }
 
     @Test
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowError500Test.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowError500Test.java
index 5f9d20ac870d..3333e52b1812 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowError500Test.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowError500Test.java
@@ -22,7 +22,7 @@ import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.component.mock.MockEndpoint;
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class UndertowError500Test extends BaseUndertowTest {
 
@@ -30,12 +30,8 @@ public class UndertowError500Test extends BaseUndertowTest {
     public void testHttp500Error() throws Exception {
         getMockEndpoint("mock:input").expectedBodiesReceived("Hello World");
 
-        try {
-            template.requestBody("http://localhost:{{port}}/foo", "Hello World", String.class);
-            fail("Should have failed");
-        } catch (CamelExecutionException e) {
-
-        }
+        assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("http://localhost:{{port}}/foo", "Hello World", String.class));
 
         MockEndpoint.assertIsSatisfied(context);
     }
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHandlersSpringTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHandlersSpringTest.java
index 10327cc5ca4c..e49a2fcab0e4 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHandlersSpringTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHandlersSpringTest.java
@@ -34,7 +34,7 @@ import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit.jupiter.SpringExtension;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 @ExtendWith(SpringExtension.class)
 @ContextConfiguration(locations = { "/HandlersSpringTest.xml" })
@@ -76,19 +76,12 @@ public class UndertowHandlersSpringTest {
         mockEndpoint.expectedBodiesReceived("Hello World");
         // username:password is guest:secret
         String auth = "Basic Z3Vlc3Q6c2Vjc";
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             String out = template.requestBodyAndHeader("undertow:http://localhost:" + port + "/spring", "Hello World",
                     "Authorization", auth, String.class);
-            fail("Should send back 401");
-            assertEquals("Bye World", out);
-
-            mockEndpoint.assertIsSatisfied();
-
-        } catch (CamelExecutionException e) {
-            HttpOperationFailedException cause = (HttpOperationFailedException) e.getCause();
-            assertEquals(401, cause.getStatusCode());
-        }
-
+        });
+        HttpOperationFailedException cause = (HttpOperationFailedException) e.getCause();
+        assertEquals(401, cause.getStatusCode());
     }
 
     public Integer getPort() {
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHttp2Test.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHttp2Test.java
index e3ed785b985e..cb2127104d46 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHttp2Test.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowHttp2Test.java
@@ -28,7 +28,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class UndertowHttp2Test extends BaseUndertowTest {
     private static final Logger LOG = LoggerFactory.getLogger(UndertowHttp2Test.class);
@@ -41,16 +40,11 @@ public class UndertowHttp2Test extends BaseUndertowTest {
         final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
         httpClient.start();
 
-        try {
-            final ContentResponse resp = httpClient.GET("http://localhost:" + getPort() + "/myapp");
+        final ContentResponse resp = httpClient.GET("http://localhost:" + getPort() + "/myapp");
 
-            assertEquals(200, resp.getStatus());
-            assertEquals(HttpVersion.HTTP_2, resp.getVersion());
-            assertEquals(RESPONSE, new String(resp.getContent()));
-        } catch (Exception ex) {
-            LOG.error(ex.getMessage(), ex);
-            fail("HTTP2 endpoint not exposed!, maybe it's not supported?");
-        }
+        assertEquals(200, resp.getStatus());
+        assertEquals(HttpVersion.HTTP_2, resp.getVersion());
+        assertEquals(RESPONSE, new String(resp.getContent()));
     }
 
     @Override
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowPrefixMatchingTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowPrefixMatchingTest.java
index 5d9bd49e7191..bc27dc676dd0 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowPrefixMatchingTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowPrefixMatchingTest.java
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class UndertowPrefixMatchingTest extends BaseUndertowTest {
 
@@ -36,13 +36,10 @@ public class UndertowPrefixMatchingTest extends BaseUndertowTest {
 
     @Test
     public void failsOnPrefixPath() {
-        try {
-            template.requestBody("http://localhost:{{port}}/myapp", "Hello Camel!");
-            fail("Should fail, something is wrong");
-        } catch (CamelExecutionException ex) {
-            HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, ex.getCause());
-            assertEquals(404, cause.getStatusCode());
-        }
+        CamelExecutionException ex = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("http://localhost:{{port}}/myapp", "Hello Camel!"));
+        HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, ex.getCause());
+        assertEquals(404, cause.getStatusCode());
     }
 
     @Test
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowSuspendResumeTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowSuspendResumeTest.java
index fd39bde0c78c..1321a2e8f907 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowSuspendResumeTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/UndertowSuspendResumeTest.java
@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class UndertowSuspendResumeTest extends BaseUndertowTest {
 
@@ -43,13 +43,9 @@ public class UndertowSuspendResumeTest extends BaseUndertowTest {
         // suspend
         consumer.suspend();
 
-        try {
-            template.requestBody(serverUri, "Moon", String.class);
-            fail("Should throw exception");
-        } catch (Exception e) {
-            HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(503, cause.getStatusCode());
-        }
+        Exception e = assertThrows(Exception.class, () -> template.requestBody(serverUri, "Moon", String.class));
+        HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(503, cause.getStatusCode());
 
         // resume
         consumer.resume();
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpBindingModeXmlTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpBindingModeXmlTest.java
index b450283b0e97..086e93492d66 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpBindingModeXmlTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpBindingModeXmlTest.java
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class RestUndertowHttpBindingModeXmlTest extends BaseUndertowTest {
 
@@ -52,12 +52,7 @@ public class RestUndertowHttpBindingModeXmlTest extends BaseUndertowTest {
 
         // we bind to xml, but send in json, which is not possible
         String body = "{\"id\": 123, \"name\": \"Donald Duck\"}";
-        try {
-            template.sendBody("http://localhost:" + getPort() + "/users/new", body);
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            // expected
-        }
+        assertThrows(Exception.class, () -> template.sendBody("http://localhost:" + getPort() + "/users/new", body));
 
         MockEndpoint.assertIsSatisfied(context);
     }
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowMethodNotAllowedTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowMethodNotAllowedTest.java
index 2ad8527c12fa..e1da3f17df74 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowMethodNotAllowedTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowMethodNotAllowedTest.java
@@ -24,30 +24,24 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class RestUndertowMethodNotAllowedTest extends BaseUndertowTest {
 
     @Test
     public void testPostMethodNotAllowed() {
-        try {
-            template.sendBodyAndHeader("http://localhost:" + getPort() + "/users/123/basic", "body", Exchange.HTTP_METHOD,
-                    "POST");
-            fail("Shall not pass!");
-        } catch (Exception e) {
-            HttpOperationFailedException hofe = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(405, hofe.getStatusCode());
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> template.sendBodyAndHeader("http://localhost:" + getPort() + "/users/123/basic", "body",
+                        Exchange.HTTP_METHOD,
+                        "POST"));
+        HttpOperationFailedException hofe = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(405, hofe.getStatusCode());
     }
 
     @Test
     public void testGetMethodAllowed() {
-        try {
-            template.sendBodyAndHeader("http://localhost:" + getPort() + "/users/123/basic", "body", Exchange.HTTP_METHOD,
-                    "GET");
-        } catch (Exception e) {
-            fail("Shall pass with GET http method!");
-        }
+        template.sendBodyAndHeader("http://localhost:" + getPort() + "/users/123/basic", "body", Exchange.HTTP_METHOD,
+                "GET");
     }
 
     @Override
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderHttpHandlerTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderHttpHandlerTest.java
index ae96a6ab4f92..58a9994adeb4 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderHttpHandlerTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderHttpHandlerTest.java
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Basic tests with securityProvider, tests whether securityProvider allows or denies access.
@@ -42,14 +42,9 @@ public class SecurityProviderHttpHandlerTest extends AbstractSecurityProviderTes
     public void testNullHttpHandler() {
         securityConfiguration.setRoleToAssign("user");
 
-        try {
-            template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
-
-            fail("Should throw exception");
-
-        } catch (CamelExecutionException e) {
-            HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(StatusCodes.METHOD_NOT_ALLOWED, he.getStatusCode());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class));
+        HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(StatusCodes.METHOD_NOT_ALLOWED, he.getStatusCode());
     }
 }
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderNoAcceptanceTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderNoAcceptanceTest.java
index c81eb154bd11..c5669be6798c 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderNoAcceptanceTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderNoAcceptanceTest.java
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Test of basic securityProvider scenario, when provider does not accepts security configuration.
@@ -45,14 +45,9 @@ public class SecurityProviderNoAcceptanceTest extends AbstractSecurityProviderTe
 
         getMockEndpoint("mock:input").expectedHeaderReceived(Exchange.HTTP_METHOD, "GET");
 
-        try {
-            template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
-
-            fail("Should throw exception");
-
-        } catch (CamelExecutionException e) {
-            HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class));
+        HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
     }
 }
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderRolesFromComponentTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderRolesFromComponentTest.java
index 41813e4aa6a5..fab257909369 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderRolesFromComponentTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderRolesFromComponentTest.java
@@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Tests whether security provider parameters defined in component are used.
@@ -62,15 +62,10 @@ public class SecurityProviderRolesFromComponentTest extends AbstractSecurityProv
 
         getMockEndpoint("mock:input").expectedHeaderReceived(Exchange.HTTP_METHOD, "GET");
 
-        try {
-            template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
-
-            fail("Should throw exception");
-
-        } catch (CamelExecutionException e) {
-            HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class));
+        HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
     }
 
     @Override
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderTest.java
index 95dcf632cb5f..e10d9c0fefc1 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderTest.java
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Basic tests with securityProvider, tests whether securityProvider allows or denies access.
@@ -51,15 +51,10 @@ public class SecurityProviderTest extends AbstractSecurityProviderTest {
 
         getMockEndpoint("mock:input").expectedHeaderReceived(Exchange.HTTP_METHOD, "GET");
 
-        try {
-            template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
-
-            fail("Should throw exception");
-
-        } catch (CamelExecutionException e) {
-            HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class));
+        HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
     }
 
 }
diff --git a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderWithoutProviderTest.java b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderWithoutProviderTest.java
index a986c8169b1e..6009a971a47e 100644
--- a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderWithoutProviderTest.java
+++ b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/SecurityProviderWithoutProviderTest.java
@@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Test of basic securityProvider scenario, when provider does not accepts security configuration.
@@ -50,14 +50,9 @@ public class SecurityProviderWithoutProviderTest extends AbstractSecurityProvide
 
         getMockEndpoint("mock:input").expectedHeaderReceived(Exchange.HTTP_METHOD, "GET");
 
-        try {
-            template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
-
-            fail("Should throw exception");
-
-        } catch (CamelExecutionException e) {
-            HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class));
+        HttpOperationFailedException he = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(StatusCodes.FORBIDDEN, he.getStatusCode());
     }
 }


(camel) 06/36: CAMEL-21196: modernize exception-based assertions in camel-jq

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit c96243b9738da428991afeca82afdad7c740cff3
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:23:42 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jq
---
 .../camel/component/hl7/HL7ValidateTest.java       | 32 ++++++++++------------
 .../camel/language/jq/JqLanguageValidateTest.java  | 10 +++----
 2 files changed, 18 insertions(+), 24 deletions(-)

diff --git a/components/camel-hl7/src/test/java/org/apache/camel/component/hl7/HL7ValidateTest.java b/components/camel-hl7/src/test/java/org/apache/camel/component/hl7/HL7ValidateTest.java
index a9e4a28e8dff..56f5495dc59d 100644
--- a/components/camel-hl7/src/test/java/org/apache/camel/component/hl7/HL7ValidateTest.java
+++ b/components/camel-hl7/src/test/java/org/apache/camel/component/hl7/HL7ValidateTest.java
@@ -40,8 +40,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class HL7ValidateTest extends CamelTestSupport {
 
@@ -54,15 +54,13 @@ public class HL7ValidateTest extends CamelTestSupport {
         mock.expectedMessageCount(0);
 
         String body = createHL7AsString();
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.sendBody("direct:unmarshalFailed", body);
-            fail("Should have thrown exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(HL7Exception.class, e.getCause());
-            assertIsInstanceOf(DataTypeException.class, e.getCause());
-            assertTrue(e.getCause().getMessage().startsWith("ca.uhn.hl7v2.validation.ValidationException: Validation failed:"),
-                    "Should be a validation error message");
-        }
+        });
+        assertIsInstanceOf(HL7Exception.class, e.getCause());
+        assertIsInstanceOf(DataTypeException.class, e.getCause());
+        assertTrue(e.getCause().getMessage().startsWith("ca.uhn.hl7v2.validation.ValidationException: Validation failed:"),
+                "Should be a validation error message");
 
         MockEndpoint.assertIsSatisfied(context);
     }
@@ -95,16 +93,14 @@ public class HL7ValidateTest extends CamelTestSupport {
         mock.expectedMessageCount(0);
 
         Message message = createADT01Message();
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.sendBody("direct:start1", message);
-            fail("Should have thrown exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(HL7Exception.class, e.getCause());
-            assertIsInstanceOf(ValidationException.class, e.getCause().getCause());
-            LOG.error("Validation failed", e.getCause().getCause());
-            assertTrue(e.getCause().getCause().getMessage().startsWith("Validation failed:"),
-                    "Should be a validation error message");
-        }
+        });
+        assertIsInstanceOf(HL7Exception.class, e.getCause());
+        assertIsInstanceOf(ValidationException.class, e.getCause().getCause());
+        LOG.error("Validation failed", e.getCause().getCause());
+        assertTrue(e.getCause().getCause().getMessage().startsWith("Validation failed:"),
+                "Should be a validation error message");
 
         MockEndpoint.assertIsSatisfied(context);
     }
diff --git a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
index 84e5ca2e4875..95611d603132 100644
--- a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
+++ b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
@@ -20,7 +20,7 @@ import net.thisptr.jackson.jq.exception.JsonQueryException;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class JqLanguageValidateTest {
 
@@ -29,12 +29,10 @@ public class JqLanguageValidateTest {
         JqLanguage lan = new JqLanguage();
         lan.init();
         Assertions.assertTrue(lan.validateExpression(". + [{\"array\": body()}]"));
-        try {
+        JsonQueryException e = assertThrows(JsonQueryException.class, () -> {
             Assertions.assertFalse(lan.validateExpression(". ^^+ [{\"array\": body()}]"));
-            fail();
-        } catch (JsonQueryException e) {
-            Assertions.assertTrue(e.getMessage().startsWith("Cannot compile query"));
-        }
+        });
+        Assertions.assertTrue(e.getMessage().startsWith("Cannot compile query"));
     }
 
 }


(camel) 22/36: CAMEL-21196: modernize exception-based assertions in camel-file-watch

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 85d808b3123dcb5f44edcf0ea46adb5285a99a91
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:39:49 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-file-watch
---
 .../component/file/watch/FileWatchComponentNegativeTest.java      | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/components/camel-file-watch/src/test/java/org/apache/camel/component/file/watch/FileWatchComponentNegativeTest.java b/components/camel-file-watch/src/test/java/org/apache/camel/component/file/watch/FileWatchComponentNegativeTest.java
index 7e14bf64c2ac..ef2be1b4cadd 100644
--- a/components/camel-file-watch/src/test/java/org/apache/camel/component/file/watch/FileWatchComponentNegativeTest.java
+++ b/components/camel-file-watch/src/test/java/org/apache/camel/component/file/watch/FileWatchComponentNegativeTest.java
@@ -21,23 +21,21 @@ import java.nio.file.Paths;
 import org.apache.camel.builder.RouteBuilder;
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class FileWatchComponentNegativeTest extends FileWatchComponentTestBase {
 
     @Test
     public void testNonExistentDirectory() throws Exception {
         String nonExistentDirectory = Paths.get(testPath(), "nonExistentDirectory").toString();
-        try {
+        assertThrows(Exception.class, () -> {
             context.addRoutes(new RouteBuilder() {
                 @Override
                 public void configure() {
                     from("file-watch://" + nonExistentDirectory + "?autoCreate=false").to("mock:watchAll");
                 }
             });
-            fail("Should throw exception");
-        } catch (Exception ignored) {
-        }
+        });
 
         context.addRoutes(new RouteBuilder() {
             @Override


(camel) 07/36: CAMEL-21196: modernize exception-based assertions in camel-csimple-joor

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 5bbd9175b26dc68a7df7e2c19b207553dd5e5722
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:33:49 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-csimple-joor
    
    Replace all try-catch-fail patterns with modern JUnit 5 assertThrows() patterns in:
    - OriginalSimpleTest.java (49 fail() calls converted)
    - OriginalSimpleOperatorTest.java (12 fail() calls converted)
    
    Updated imports: removed fail, added assertThrows
---
 .../csimple/joor/OriginalSimpleOperatorTest.java   | 114 +++----
 .../language/csimple/joor/OriginalSimpleTest.java  | 346 +++++++--------------
 2 files changed, 158 insertions(+), 302 deletions(-)

diff --git a/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleOperatorTest.java b/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleOperatorTest.java
index bc0e81d3efd0..36cf952228ae 100644
--- a/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleOperatorTest.java
+++ b/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleOperatorTest.java
@@ -23,7 +23,7 @@ import org.apache.camel.test.junit5.LanguageTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class OriginalSimpleOperatorTest extends LanguageTestSupport {
 
@@ -587,12 +587,9 @@ public class OriginalSimpleOperatorTest extends LanguageTestSupport {
         assertPredicate("${in.header.foo} is 'String'", true);
         assertPredicate("${in.header.foo} is 'Integer'", false);
 
-        try {
-            assertPredicate("${in.header.foo} is com.mycompany.DoesNotExist", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(20, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e0 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} is com.mycompany.DoesNotExist", false));
+        assertEquals(20, e0.getIndex());
     }
 
     @Test
@@ -607,18 +604,13 @@ public class OriginalSimpleOperatorTest extends LanguageTestSupport {
         assertPredicate("${in.header.foo} !is 'String'", false);
         assertPredicate("${in.header.foo} !is 'Integer'", true);
 
-        try {
-            assertPredicate("${in.header.foo} not is com.mycompany.DoesNotExist", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(24, e.getIndex());
-        }
-        try {
-            assertPredicate("${in.header.foo} !is com.mycompany.DoesNotExist", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(21, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e1 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} not is com.mycompany.DoesNotExist", false));
+        assertEquals(24, e1.getIndex());
+
+        SimpleIllegalSyntaxException e2 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} !is com.mycompany.DoesNotExist", false));
+        assertEquals(21, e2.getIndex());
     }
 
     @Test
@@ -632,26 +624,17 @@ public class OriginalSimpleOperatorTest extends LanguageTestSupport {
         assertPredicate("${bean:generator.generateId} range '120..122'", false);
         assertPredicate("${bean:generator.generateId} range '124..130'", false);
 
-        try {
-            assertPredicate("${in.header.foo} range abc..200", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(23, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e1 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} range abc..200", false));
+        assertEquals(23, e1.getIndex());
 
-        try {
-            assertPredicate("${in.header.foo} range abc..", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(23, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e2 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} range abc..", false));
+        assertEquals(23, e2.getIndex());
 
-        try {
-            assertPredicate("${in.header.foo} range 100.200", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(30, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e3 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} range 100.200", false));
+        assertEquals(30, e3.getIndex());
 
         assertPredicate("${in.header.bar} range '100..200' && ${in.header.foo} == 'abc'", true);
         assertPredicate("${in.header.bar} range '200..300' && ${in.header.foo} == 'abc'", false);
@@ -677,44 +660,29 @@ public class OriginalSimpleOperatorTest extends LanguageTestSupport {
         assertPredicate("${bean:generator.generateId} !range '120..122'", true);
         assertPredicate("${bean:generator.generateId} !range '124..130'", true);
 
-        try {
-            assertPredicate("${in.header.foo} not range abc..200", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(27, e.getIndex());
-        }
-        try {
-            assertPredicate("${in.header.foo} !range abc..200", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(24, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e1 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} not range abc..200", false));
+        assertEquals(27, e1.getIndex());
 
-        try {
-            assertPredicate("${in.header.foo} not range abc..", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(27, e.getIndex());
-        }
-        try {
-            assertPredicate("${in.header.foo} !range abc..", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(24, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e2 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} !range abc..200", false));
+        assertEquals(24, e2.getIndex());
 
-        try {
-            assertPredicate("${in.header.foo} not range 100.200", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(34, e.getIndex());
-        }
-        try {
-            assertPredicate("${in.header.foo} !range 100.200", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(31, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e3 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} not range abc..", false));
+        assertEquals(27, e3.getIndex());
+
+        SimpleIllegalSyntaxException e4 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} !range abc..", false));
+        assertEquals(24, e4.getIndex());
+
+        SimpleIllegalSyntaxException e5 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} not range 100.200", false));
+        assertEquals(34, e5.getIndex());
+
+        SimpleIllegalSyntaxException e6 = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${in.header.foo} !range 100.200", false));
+        assertEquals(31, e6.getIndex());
     }
 
     @Test
diff --git a/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleTest.java b/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleTest.java
index de8e4e40c935..2d0eeed4ab73 100644
--- a/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleTest.java
+++ b/components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleTest.java
@@ -157,21 +157,13 @@ public class OriginalSimpleTest extends LanguageTestSupport {
     @Test
     public void testEmptyExpression() {
         assertExpression("", "");
-        try {
-            assertExpression(null, null);
-            fail("Should have thrown exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals("expression must be specified", e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> assertExpression(null, null));
+        assertEquals("expression must be specified", e.getMessage());
 
         assertPredicate("", false);
         assertPredicate(" ", false);
-        try {
-            assertPredicate(null, false);
-            fail("Should have thrown exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals("expression must be specified", e.getMessage());
-        }
+        e = assertThrows(IllegalArgumentException.class, () -> assertPredicate(null, false));
+        assertEquals("expression must be specified", e.getMessage());
     }
 
     @Test
@@ -435,12 +427,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         // there is no upper case method on byte array, but we can convert to
         // String as below
-        try {
-            assertPredicate("${bodyAs(byte[]).toUpperCase()} == \"HELLO WORLD\"", true);
-            fail("Should throw exception");
-        } catch (JoorCSimpleCompilationException e) {
-            assertTrue(e.getCause().getMessage().contains("method toUpperCase()"));
-        }
+        JoorCSimpleCompilationException e = assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertPredicate("${bodyAs(byte[]).toUpperCase()} == \"HELLO WORLD\"", true));
+        assertTrue(e.getCause().getMessage().contains("method toUpperCase()"));
 
         assertPredicate("${bodyAs(String)} == \"hello world\"", true);
         assertPredicate("${bodyAs(String).toUpperCase()} == \"HELLO WORLD\"", true);
@@ -456,12 +445,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         // there is no upper case method on byte array, but we can convert to
         // String as below
-        try {
-            assertPredicate("${bodyAs(byte[]).toUpperCase()} == \"HELLO WORLD\"", true);
-            fail("Should throw exception");
-        } catch (JoorCSimpleCompilationException e) {
-            assertTrue(e.getCause().getMessage().contains("method toUpperCase()"));
-        }
+        JoorCSimpleCompilationException e = assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertPredicate("${bodyAs(byte[]).toUpperCase()} == \"HELLO WORLD\"", true));
+        assertTrue(e.getCause().getMessage().contains("method toUpperCase()"));
 
         assertPredicate("${mandatoryBodyAs(String)} == \"hello world\"", true);
         assertPredicate("${mandatoryBodyAs(String).toUpperCase()} == \"HELLO WORLD\"", true);
@@ -521,12 +507,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         assertExpression("${mandatoryBodyAsIndex(OrderLine, '[0][noname]').getId}", 789);
         assertExpression("${mandatoryBodyAsIndex(OrderLine, '[0][noname]').getName}", null);
-        try {
-            assertExpression("${mandatoryBodyAsIndex(OrderLine, '[0][doesnotexists]').getName}", null);
-            fail("Should throw exception");
-        } catch (Exception e) {
-            assertIsInstanceOf(InvalidPayloadException.class, e.getCause());
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> assertExpression("${mandatoryBodyAsIndex(OrderLine, '[0][doesnotexists]').getName}", null));
+        assertIsInstanceOf(InvalidPayloadException.class, e.getCause());
 
         assertExpression("${mandatoryBodyAs(OrderLine)[0][camel].id}", 123);
         assertExpression("${mandatoryBodyAs(OrderLine)[0][camel].name}", "Camel in Action");
@@ -543,13 +526,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         assertExpression("${exchangeProperty.wicket[0]}", "Camel in Action");
         assertExpression("${exchangeProperty.wicket[1]}", "ActiveMQ in Action");
-        try {
-            assertExpression("${exchangeProperty.wicket[2]}", "");
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
-            assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> assertExpression("${exchangeProperty.wicket[2]}", ""));
+        IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
+        assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
         assertExpression("${exchangeProperty.unknown[cool]}", null);
     }
 
@@ -563,13 +543,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         assertExpression("${exchangePropertyAsIndex(wicket, OrderLine, '0').getId}", 123);
         assertExpression("${exchangePropertyAsIndex(wicket, OrderLine, '1').getName}", "ActiveMQ in Action");
 
-        try {
-            assertExpression("${exchangePropertyAsIndex(wicket, OrderLine, '2')}", "");
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
-            assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> assertExpression("${exchangePropertyAsIndex(wicket, OrderLine, '2')}", ""));
+        IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, ex.getCause());
+        assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
         assertExpression("${exchangeProperty.unknown[cool]}", null);
         assertExpression("${exchangePropertyAsIndex(unknown, OrderLine, 'cool')}", null);
     }
@@ -624,26 +601,20 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
     @Test
     public void testOGNLPropertyMapIllegalSyntax() {
-        try {
-            assertExpression("${exchangeProperty.foobar[bar}", null);
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage()
-                    .startsWith(
-                            "Valid syntax: ${exchangeProperty.name[key]} was: exchangeProperty.foobar[bar at location 0"));
-        }
+        ExpressionIllegalSyntaxException ex1 = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("${exchangeProperty.foobar[bar}", null));
+        assertTrue(ex1.getMessage()
+                .startsWith(
+                        "Valid syntax: ${exchangeProperty.name[key]} was: exchangeProperty.foobar[bar at location 0"));
     }
 
     @Test
     public void testOGNLExchangePropertyMapIllegalSyntax() {
-        try {
-            assertExpression("${exchangeProperty.foobar[bar}", null);
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            assertTrue(e.getMessage()
-                    .startsWith(
-                            "Valid syntax: ${exchangeProperty.name[key]} was: exchangeProperty.foobar[bar at location 0"));
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> assertExpression("${exchangeProperty.foobar[bar}", null));
+        assertTrue(ex.getMessage()
+                .startsWith(
+                        "Valid syntax: ${exchangeProperty.name[key]} was: exchangeProperty.foobar[bar at location 0"));
     }
 
     @Test
@@ -689,12 +660,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         assertExpression("${date:exchangeProperty.birthday:yyyyMMdd}", "19760622");
         assertExpression("${date:exchangeProperty.birthday+24h:yyyyMMdd}", "19760623");
 
-        try {
-            assertExpression("${date:yyyyMMdd}", "19740420");
-            fail("Should thrown an exception");
-        } catch (Exception e) {
-            assertEquals("Command not supported for dateExpression: yyyyMMdd", e.getCause().getMessage());
-        }
+        Exception ex = assertThrows(Exception.class,
+                () -> assertExpression("${date:yyyyMMdd}", "19740420"));
+        assertEquals("Command not supported for dateExpression: yyyyMMdd", ex.getCause().getMessage());
     }
 
     @Test
@@ -793,12 +761,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
     @Test
     public void testInvalidComplexExpression() {
-        try {
-            assertExpression("hey ${foo", "bad expression!");
-            fail("Should have thrown an exception!");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(8, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertExpression("hey ${foo", "bad expression!"));
+        assertEquals(8, e.getIndex());
     }
 
     @Test
@@ -849,12 +814,8 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         assertExpression("${bodyAs(int)}", 456);
         assertExpression("${bodyAs(\"int\")}", 456);
 
-        try {
-            assertExpression("${bodyAs(XXX)}", 456);
-            fail("Should have thrown an exception");
-        } catch (JoorCSimpleCompilationException e) {
-            // expected
-        }
+        assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertExpression("${bodyAs(XXX)}", 456));
     }
 
     @Test
@@ -863,12 +824,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         assertExpression("${mandatoryBodyAs(\"String\")}", "<hello id='m123'>world!</hello>");
 
         exchange.getIn().setBody(null);
-        try {
-            assertExpression("${mandatoryBodyAs(\"String\")}", "");
-            fail("Should have thrown exception");
-        } catch (ExpressionEvaluationException e) {
-            assertIsInstanceOf(InvalidPayloadException.class, e.getCause());
-        }
+        ExpressionEvaluationException e = assertThrows(ExpressionEvaluationException.class,
+                () -> assertExpression("${mandatoryBodyAs(\"String\")}", ""));
+        assertIsInstanceOf(InvalidPayloadException.class, e.getCause());
 
         exchange.getIn().setBody(456);
         assertExpression("${mandatoryBodyAs(Integer)}", 456);
@@ -876,12 +834,8 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         assertExpression("${mandatoryBodyAs('int')}", 456);
         assertExpression("${mandatoryBodyAs(\"int\")}", 456);
 
-        try {
-            assertExpression("${mandatoryBodyAs(XXX)}", 456);
-            fail("Should have thrown an exception");
-        } catch (JoorCSimpleCompilationException e) {
-            // expected
-        }
+        assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertExpression("${mandatoryBodyAs(XXX)}", 456));
     }
 
     @Test
@@ -939,12 +893,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         // set an empty body
         exchange.getIn().setBody(null);
 
-        try {
-            assertPredicate("${body} is null", false);
-            fail("Should have thrown an exception");
-        } catch (SimpleIllegalSyntaxException e) {
-            assertEquals(11, e.getIndex());
-        }
+        SimpleIllegalSyntaxException e = assertThrows(SimpleIllegalSyntaxException.class,
+                () -> assertPredicate("${body} is null", false));
+        assertEquals(11, e.getIndex());
     }
 
     @Test
@@ -989,50 +940,30 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         assertExpression("${headerAs(unknown,String)}", null);
 
-        try {
-            assertExpression("${headerAs(unknown String)}", null);
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage().startsWith("Valid syntax: ${headerAs(key, type)} was: headerAs(unknown String)"));
-        }
+        ExpressionIllegalSyntaxException e1 = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("${headerAs(unknown String)}", null));
+        assertTrue(e1.getMessage().startsWith("Valid syntax: ${headerAs(key, type)} was: headerAs(unknown String)"));
 
-        try {
-            assertExpression("${headerAs(fool,String).test}", null);
-            fail("Should have thrown an exception");
-        } catch (JoorCSimpleCompilationException e) {
-            // expected
-        }
+        assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertExpression("${headerAs(fool,String).test}", null));
 
-        try {
-            assertExpression("${headerAs(bar,XXX)}", 123);
-            fail("Should have thrown an exception");
-        } catch (JoorCSimpleCompilationException e) {
-            // expected
-        }
+        assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertExpression("${headerAs(bar,XXX)}", 123));
     }
 
     @Test
     public void testIllegalSyntax() {
-        try {
-            assertExpression("hey ${xxx} how are you?", "");
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage().startsWith("Unknown function: xxx at location 4"));
-        }
+        ExpressionIllegalSyntaxException e1 = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("hey ${xxx} how are you?", ""));
+        assertTrue(e1.getMessage().startsWith("Unknown function: xxx at location 4"));
 
-        try {
-            assertExpression("${xxx}", "");
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage().startsWith("Unknown function: xxx at location 0"));
-        }
+        ExpressionIllegalSyntaxException e2 = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("${xxx}", ""));
+        assertTrue(e2.getMessage().startsWith("Unknown function: xxx at location 0"));
 
-        try {
-            assertExpression("${bodyAs(xxx}", "");
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage().startsWith("Valid syntax: ${bodyAs(type)} was: bodyAs(xxx"));
-        }
+        ExpressionIllegalSyntaxException e3 = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("${bodyAs(xxx}", ""));
+        assertTrue(e3.getMessage().startsWith("Valid syntax: ${bodyAs(type)} was: bodyAs(xxx"));
     }
 
     @Test
@@ -1044,13 +975,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         assertExpression("${header.wicket[0]}", "Camel in Action");
         assertExpression("${header.wicket[1]}", "ActiveMQ in Action");
-        try {
-            assertExpression("${header.wicket[2]}", "");
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
-            assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
-        }
+        Exception ex1 = assertThrows(Exception.class,
+                () -> assertExpression("${header.wicket[2]}", ""));
+        IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, ex1.getCause());
+        assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
         assertExpression("${header.unknown[cool]}", null);
     }
 
@@ -1063,13 +991,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         assertExpression("${headerAsIndex(wicket, OrderLine, 0).getId}", 123);
         assertExpression("${headerAsIndex(wicket, OrderLine, 1).getName}", "ActiveMQ in Action");
-        try {
-            assertExpression("${header.wicket[2]}", "");
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
-            assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause.getMessage());
-        }
+        Exception ex2 = assertThrows(Exception.class,
+                () -> assertExpression("${header.wicket[2]}", ""));
+        IndexOutOfBoundsException cause2 = assertIsInstanceOf(IndexOutOfBoundsException.class, ex2.getCause());
+        assertEquals(INDEX_OUT_OF_BOUNDS_ERROR_MSG, cause2.getMessage());
         assertExpression("${header.unknown[cool]}", null);
     }
 
@@ -1106,12 +1031,9 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
     @Test
     public void testOGNLHeaderMapIllegalSyntax() {
-        try {
-            assertExpression("${header.foo[bar}", null);
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage().startsWith("Valid syntax: ${header.name[key]} was: header.foo[bar"));
-        }
+        ExpressionIllegalSyntaxException e = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("${header.foo[bar}", null));
+        assertTrue(e.getMessage().startsWith("Valid syntax: ${header.name[key]} was: header.foo[bar"));
     }
 
     @Test
@@ -1380,13 +1302,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         exchange.getIn().setBody(order);
 
-        try {
-            assertExpression("${bodyAs(Order).getLines[3].getId}", 123);
-            fail("Should have thrown an exception");
-        } catch (ExpressionEvaluationException e) {
-            IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
-            assertEquals("Index 3 out of bounds for length 2", cause.getMessage());
-        }
+        ExpressionEvaluationException ex1 = assertThrows(ExpressionEvaluationException.class,
+                () -> assertExpression("${bodyAs(Order).getLines[3].getId}", 123));
+        IndexOutOfBoundsException cause1 = assertIsInstanceOf(IndexOutOfBoundsException.class, ex1.getCause());
+        assertEquals("Index 3 out of bounds for length 2", cause1.getMessage());
     }
 
     @Test
@@ -1398,13 +1317,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         exchange.getIn().setBody(order);
 
-        try {
-            assertExpression("${bodyAs(Order).lines[3].id}", 123);
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
-            assertTrue(cause.getMessage().startsWith("Index 3 out of bounds for length 2"));
-        }
+        Exception ex2 = assertThrows(Exception.class,
+                () -> assertExpression("${bodyAs(Order).lines[3].id}", 123));
+        IndexOutOfBoundsException cause2 = assertIsInstanceOf(IndexOutOfBoundsException.class, ex2.getCause());
+        assertTrue(cause2.getMessage().startsWith("Index 3 out of bounds for length 2"));
     }
 
     @Disabled("Investigation pending - see CAMEL-19681")
@@ -1443,13 +1359,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         exchange.getIn().setBody(order);
 
-        try {
-            assertExpression("${bodyAs(Order).getLines[0]?.getRating}", "");
-            fail("Should have thrown exception");
-        } catch (RuntimeBeanExpressionException e) {
-            MethodNotFoundException cause = assertIsInstanceOf(MethodNotFoundException.class, e.getCause());
-            assertEquals("getRating", cause.getMethodName());
-        }
+        RuntimeBeanExpressionException e = assertThrows(RuntimeBeanExpressionException.class,
+                () -> assertExpression("${bodyAs(Order).getLines[0]?.getRating}", ""));
+        MethodNotFoundException cause = assertIsInstanceOf(MethodNotFoundException.class, e.getCause());
+        assertEquals("getRating", cause.getMethodName());
     }
 
     @Disabled("Investigation pending - see CAMEL-19681")
@@ -1462,13 +1375,10 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         exchange.getIn().setBody(order);
 
-        try {
-            assertExpression("${bodyAs(Order).lines[0]?.rating}", "");
-            fail("Should have thrown exception");
-        } catch (RuntimeBeanExpressionException e) {
-            MethodNotFoundException cause = assertIsInstanceOf(MethodNotFoundException.class, e.getCause());
-            assertEquals("rating", cause.getMethodName());
-        }
+        RuntimeBeanExpressionException e = assertThrows(RuntimeBeanExpressionException.class,
+                () -> assertExpression("${bodyAs(Order).lines[0]?.rating}", ""));
+        MethodNotFoundException cause = assertIsInstanceOf(MethodNotFoundException.class, e.getCause());
+        assertEquals("rating", cause.getMethodName());
     }
 
     @Disabled("Investigation pending - see CAMEL-19681")
@@ -1488,16 +1398,13 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         // using null safe to avoid the NPE
         assertExpression("${bodyAs(Animal).getFriend?.getFriend.getName}", null);
-        try {
-            // without null safe we get an NPE
-            assertExpression("${bodyAs(Animal).getFriend.getFriend.getName}", "");
-            fail("Should have thrown exception");
-        } catch (RuntimeBeanExpressionException e) {
-            assertEquals(
-                    "Failed to invoke method: .getFriend.getFriend.getName on org.apache.camel.language.simple.SimpleTest.Animal"
-                         + " due last method returned null and therefore cannot continue to invoke method .getName on a null instance",
-                    e.getMessage());
-        }
+        // without null safe we get an NPE
+        RuntimeBeanExpressionException e = assertThrows(RuntimeBeanExpressionException.class,
+                () -> assertExpression("${bodyAs(Animal).getFriend.getFriend.getName}", ""));
+        assertEquals(
+                "Failed to invoke method: .getFriend.getFriend.getName on org.apache.camel.language.simple.SimpleTest.Animal"
+                     + " due last method returned null and therefore cannot continue to invoke method .getName on a null instance",
+                e.getMessage());
     }
 
     @Disabled("Investigation pending - see CAMEL-19681")
@@ -1518,15 +1425,12 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         // using null safe to avoid the NPE
         assertExpression("${bodyAs(Animal).friend?.friend.name}", null);
-        try {
-            // without null safe we get an NPE
-            assertExpression("${bodyAs(Animal).friend.friend.name}", "");
-            fail("Should have thrown exception");
-        } catch (RuntimeBeanExpressionException e) {
-            assertEquals("Failed to invoke method: .friend.friend.name on org.apache.camel.language.simple.SimpleTest.Animal"
-                         + " due last method returned null and therefore cannot continue to invoke method .name on a null instance",
-                    e.getMessage());
-        }
+        // without null safe we get an NPE
+        RuntimeBeanExpressionException e = assertThrows(RuntimeBeanExpressionException.class,
+                () -> assertExpression("${bodyAs(Animal).friend.friend.name}", ""));
+        assertEquals("Failed to invoke method: .friend.friend.name on org.apache.camel.language.simple.SimpleTest.Animal"
+                     + " due last method returned null and therefore cannot continue to invoke method .name on a null instance",
+                e.getMessage());
     }
 
     @Test
@@ -1973,18 +1877,12 @@ public class OriginalSimpleTest extends LanguageTestSupport {
         Expression expression1 = context.resolveLanguage("csimple").createExpression("${random( 10)}");
         assertTrue(0 <= expression1.evaluate(exchange, Integer.class) && expression1.evaluate(exchange, Integer.class) < max);
 
-        try {
-            assertExpression("${random(10,21,30)}", null);
-            fail("Should have thrown exception");
-        } catch (JoorCSimpleCompilationException e) {
-            // expected
-        }
-        try {
-            assertExpression("${random()}", null);
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            assertEquals("Valid syntax: ${random(min,max)} or ${random(max)} was: random()", e.getCause().getMessage());
-        }
+        assertThrows(JoorCSimpleCompilationException.class,
+                () -> assertExpression("${random(10,21,30)}", null));
+
+        Exception e = assertThrows(Exception.class,
+                () -> assertExpression("${random()}", null));
+        assertEquals("Valid syntax: ${random(min,max)} or ${random(max)} was: random()", e.getCause().getMessage());
 
         exchange.getIn().setHeader("max", 20);
         Expression expression3 = context.resolveLanguage("csimple").createExpression("${random(10,${header.max})}");
@@ -2188,26 +2086,16 @@ public class OriginalSimpleTest extends LanguageTestSupport {
 
         assertExpression("${variableAs(unknown,String)}", null);
 
-        try {
-            assertExpression("${variableAs(unknown String)}", null);
-            fail("Should have thrown an exception");
-        } catch (ExpressionIllegalSyntaxException e) {
-            assertTrue(e.getMessage().startsWith("Valid syntax: ${variableAs(key, type)} was: variableAs(unknown String)"));
-        }
+        ExpressionIllegalSyntaxException e = assertThrows(ExpressionIllegalSyntaxException.class,
+                () -> assertExpression("${variableAs(unknown String)}", null));
+        assertTrue(e.getMessage().startsWith("Valid syntax: ${variableAs(key, type)} was: variableAs(unknown String)"));
 
-        try {
-            assertExpression("${variableAs(fool,String).test}", null);
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            assertTrue(e.getMessage().startsWith("csimple-joor compilation error for class"));
-        }
+        Exception e1 = assertThrows(Exception.class,
+                () -> assertExpression("${variableAs(fool,String).test}", null));
+        assertTrue(e1.getMessage().startsWith("csimple-joor compilation error for class"));
 
-        try {
-            assertExpression("${variableAs(bar,XXX)}", 123);
-            fail("Should have thrown an exception");
-        } catch (Exception e) {
-            // expected
-        }
+        assertThrows(Exception.class,
+                () -> assertExpression("${variableAs(bar,XXX)}", 123));
     }
 
     @Test


(camel) 27/36: CAMEL-21196: modernize exception-based assertions in camel-protobuf

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 3c44341732fce3435c52ccbd4c68c436fdf43d1b
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:46:03 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-protobuf
    
    Replace try-catch-fail patterns with assertThrows in:
    - ProtobufMarshalAndUnmarshalSpringTest.java (1 occurrence)
    - ProtobufMarshalAndUnmarshalTest.java (1 occurrence)
---
 .../protobuf/ProtobufMarshalAndUnmarshalSpringTest.java        | 10 ++++------
 .../dataformat/protobuf/ProtobufMarshalAndUnmarshalTest.java   | 10 ++++------
 2 files changed, 8 insertions(+), 12 deletions(-)

diff --git a/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalSpringTest.java b/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalSpringTest.java
index cf8053189415..22f3f4002a70 100644
--- a/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalSpringTest.java
+++ b/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalSpringTest.java
@@ -27,8 +27,8 @@ import org.junit.jupiter.api.Test;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class ProtobufMarshalAndUnmarshalSpringTest extends CamelSpringTestSupport {
 
@@ -54,17 +54,15 @@ public class ProtobufMarshalAndUnmarshalSpringTest extends CamelSpringTestSuppor
 
     @Test
     public void testMarshalAndUnmarshalWithDSL3() {
-        try {
+        Exception ex = assertThrows(Exception.class, () -> {
             context.addRoutes(new RouteBuilder() {
                 @Override
                 public void configure() {
                     from("direct:unmarshalC").unmarshal().protobuf(new CamelException("wrong instance")).to("mock:reverse");
                 }
             });
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
-        }
+        });
+        assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
     }
 
     private void marshalAndUnmarshal(String inURI, String outURI) throws Exception {
diff --git a/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalTest.java b/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalTest.java
index 2b0380d41a75..6ba0700d3a4d 100644
--- a/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalTest.java
+++ b/components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalTest.java
@@ -26,8 +26,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class ProtobufMarshalAndUnmarshalTest extends CamelTestSupport {
 
@@ -48,17 +48,15 @@ public class ProtobufMarshalAndUnmarshalTest extends CamelTestSupport {
 
     @Test
     public void testMarshalAndUnmarshalWithDSL3() {
-        try {
+        Exception ex = assertThrows(Exception.class, () -> {
             context.addRoutes(new RouteBuilder() {
                 @Override
                 public void configure() {
                     from("direct:unmarshalC").unmarshal().protobuf(new CamelException("wrong instance")).to("mock:reverse");
                 }
             });
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
-        }
+        });
+        assertTrue(ex instanceof FailedToCreateRouteException, "Expect FailedToCreateRouteException");
     }
 
     private void marshalAndUnmarshal(String inURI, String outURI) throws Exception {


(camel) 16/36: CAMEL-21196: modernize exception-based assertions in camel-jpa

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit b64a59c08f782e381fc48504f48941457e12bb8a
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:21:23 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jpa
    
    Replace try-catch-fail pattern with assertThrows in JpaProducerNoBodyTest.
---
 .../apache/camel/processor/jpa/JpaProducerNoBodyTest.java    | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerNoBodyTest.java b/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerNoBodyTest.java
index 89c595bacbc4..c8a007177db5 100644
--- a/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerNoBodyTest.java
+++ b/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerNoBodyTest.java
@@ -23,19 +23,17 @@ import org.apache.camel.examples.SendEmail;
 import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class JpaProducerNoBodyTest extends AbstractJpaTest {
     protected static final String SELECT_ALL_STRING = "select x from " + SendEmail.class.getName() + " x";
 
     @Test
     public void testRouteJpa() {
-        try {
-            template.sendBody("direct:start", null);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(InvalidPayloadRuntimeException.class, e.getCause());
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody("direct:start", null),
+                "Should have thrown an exception");
+        assertIsInstanceOf(InvalidPayloadRuntimeException.class, e.getCause());
     }
 
     @Override


(camel) 11/36: CAMEL-21196: modernize exception-based assertions in camel-mllp

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit dd2d9bd94f43c7bbfa5ccf64e99c720734ecab41
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:42:54 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-mllp
---
 ...nAndHeaderRequiresClientAuthenticationTest.java |  8 +++----
 .../internal/MllpSocketBufferReadFromTest.java     | 26 +++++++++-------------
 .../mllp/internal/MllpSocketBufferTest.java        | 10 ++++-----
 .../TransactionalClientDataSourceAsyncTest.java    |  2 +-
 ...sactionalClientDataSourceNotTransactedTest.java |  2 +-
 .../TransactionalClientDataSourceTest.java         |  2 +-
 ...ctionalClientDataSourceWithOnExceptionTest.java |  2 +-
 .../TransactionalClientWithRollbackTest.java       |  2 +-
 .../SpringCamelContextStartingFailedEventTest.java |  2 +-
 .../spring/processor/SpringFilterNoChildTest.java  |  2 +-
 10 files changed, 25 insertions(+), 33 deletions(-)

diff --git a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpMutualTlsConnectionAndHeaderRequiresClientAuthenticationTest.java b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpMutualTlsConnectionAndHeaderRequiresClientAuthenticationTest.java
index 4a63d482d9c5..de0890a22cee 100644
--- a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpMutualTlsConnectionAndHeaderRequiresClientAuthenticationTest.java
+++ b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpMutualTlsConnectionAndHeaderRequiresClientAuthenticationTest.java
@@ -37,12 +37,10 @@ class MllpMutualTlsConnectionAndHeaderRequiresClientAuthenticationTest extends M
      */
     @Test
     void testSendingTlsWithNoClientCertificateToMllpConsumerWhichRequiresClientAuthentication() {
-        try {
+        CamelExecutionException e = Assertions.assertThrows(CamelExecutionException.class, () -> {
             template.sendBody(assembleEndpointUri(WITH_ONLY_TRUSTSTORE), TEST_PAYLOAD);
-            Assertions.fail("Should not be able to connect without a client certificate");
-        } catch (CamelExecutionException e) {
-            Assertions.assertInstanceOf(SSLHandshakeException.class, e.getCause().getCause().getCause());
-        }
+        });
+        Assertions.assertInstanceOf(SSLHandshakeException.class, e.getCause().getCause().getCause());
     }
 
     /**
diff --git a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferReadFromTest.java b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferReadFromTest.java
index 7ac2c8f4d5dd..e5f07e68b740 100644
--- a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferReadFromTest.java
+++ b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferReadFromTest.java
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Tests for the class.
@@ -52,14 +52,12 @@ public class MllpSocketBufferReadFromTest extends SocketBufferTestSupport {
         inputStreamStub
                 .addPacket(new SocketTimeoutException("Fake Timeout Exception"));
 
-        try {
-            endpoint.setReceiveTimeout(500);
-            endpoint.setReadTimeout(100);
+        endpoint.setReceiveTimeout(500);
+        endpoint.setReadTimeout(100);
+        assertThrows(SocketTimeoutException.class, () -> {
             instance.readFrom(socketStub);
-            fail("Should have thrown and exception");
-        } catch (SocketTimeoutException expectedEx) {
-            assertNull(instance.toByteArray());
-        }
+        });
+        assertNull(instance.toByteArray());
     }
 
     /**
@@ -74,13 +72,11 @@ public class MllpSocketBufferReadFromTest extends SocketBufferTestSupport {
                 .addPacket("BAR".getBytes())
                 .addPacket(new SocketTimeoutException("Fake Timeout Exception"));
 
-        try {
-            endpoint.setReceiveTimeout(500);
-            endpoint.setReadTimeout(100);
+        endpoint.setReceiveTimeout(500);
+        endpoint.setReadTimeout(100);
+        assertThrows(SocketTimeoutException.class, () -> {
             instance.readFrom(socketStub);
-            fail("Should have thrown and exception");
-        } catch (SocketTimeoutException expectedEx) {
-            assertNull(instance.toByteArray());
-        }
+        });
+        assertNull(instance.toByteArray());
     }
 }
diff --git a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferTest.java b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferTest.java
index 52cbeff91d25..5bb3cc012567 100644
--- a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferTest.java
+++ b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/internal/MllpSocketBufferTest.java
@@ -23,8 +23,8 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * Tests for the MllpSocketBuffer class.
@@ -36,12 +36,10 @@ public class MllpSocketBufferTest extends SocketBufferTestSupport {
      */
     @Test
     public void testConstructorWithNullEndpoing() {
-        try {
+        IllegalArgumentException expectedEx = assertThrows(IllegalArgumentException.class, () -> {
             new MllpSocketBuffer(null);
-            fail("Constructor should have thrown an exception with a null Endpoint argument");
-        } catch (IllegalArgumentException expectedEx) {
-            assertEquals("MllpEndpoint cannot be null", expectedEx.getMessage());
-        }
+        });
+        assertEquals("MllpEndpoint cannot be null", expectedEx.getMessage());
     }
 
     /**
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java
index caf0de4f4fad..1610bde47064 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceAsyncTest.java
@@ -25,8 +25,8 @@ import org.apache.camel.spring.spi.SpringTransactionPolicy;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java
index f50acc8d087c..b6ea347702ab 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceNotTransactedTest.java
@@ -22,8 +22,8 @@ import org.apache.camel.spring.SpringRouteBuilder;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Same route but not transacted
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java
index adc7cfae1825..9549be8edaf1 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTest.java
@@ -23,8 +23,8 @@ import org.apache.camel.spring.spi.SpringTransactionPolicy;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java
index 93fa621b010a..f25b50f0ec15 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceWithOnExceptionTest.java
@@ -24,8 +24,8 @@ import org.apache.camel.spring.spi.SpringTransactionPolicy;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Unit test to demonstrate the transactional client pattern.
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java
index 72af2771fc18..18b2d557d7d1 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientWithRollbackTest.java
@@ -31,8 +31,8 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
 import org.springframework.jdbc.core.JdbcTemplate;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Transactional client test with rollback in the DSL.
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java
index 2bbf66b5d289..67bd8c6c7a67 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java
@@ -25,8 +25,8 @@ import org.junit.jupiter.api.condition.OS;
 import org.springframework.context.support.AbstractXmlApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 @DisabledOnOs(OS.AIX)
 public class SpringCamelContextStartingFailedEventTest extends SpringTestSupport {
diff --git a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java
index fdee058d2c9a..16d09cbf4134 100644
--- a/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java
+++ b/components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFilterNoChildTest.java
@@ -24,8 +24,8 @@ import org.springframework.context.support.AbstractXmlApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class SpringFilterNoChildTest extends SpringTestSupport {
 


(camel) 19/36: CAMEL-21196: modernize exception-based assertions in camel-jmx

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 812660e0bb009d19322860a77d4893df63065c66
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:21:32 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jmx
    
    Replace try-catch-fail patterns with assertThrows in:
    - JMXEndpointTest (9 occurrences)
    - JMXRobustRemoteConnectionTest (1 occurrence)
    - JMXComponentTest (3 occurrences)
---
 .../camel/component/jmx/JMXComponentTest.java      | 32 ++++----
 .../camel/component/jmx/JMXEndpointTest.java       | 90 +++++++++-------------
 .../jmx/JMXRobustRemoteConnectionTest.java         | 14 ++--
 3 files changed, 54 insertions(+), 82 deletions(-)

diff --git a/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXComponentTest.java b/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXComponentTest.java
index d158f2a81bf2..55b5d16a207e 100644
--- a/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXComponentTest.java
+++ b/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXComponentTest.java
@@ -25,8 +25,8 @@ import org.junit.jupiter.api.Test;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * Test behavior in the component for initializing an endpoint. Not much here beyond checking that the code for the
@@ -63,31 +63,25 @@ public class JMXComponentTest {
 
     @Test
     public void withObjectNameAndObjectProperties() {
-        try {
-            context.getEndpoint("jmx:platform?objectDomain=FooDomain&objectName=theObjectName&key.propOne=prop1");
-            fail("expected exception");
-        } catch (ResolveEndpointFailedException e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-        }
+        ResolveEndpointFailedException e = assertThrows(ResolveEndpointFailedException.class,
+                () -> context.getEndpoint("jmx:platform?objectDomain=FooDomain&objectName=theObjectName&key.propOne=prop1"),
+                "expected exception");
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
     }
 
     @Test
     public void withoutDomain() {
-        try {
-            context.getEndpoint("jmx:platform?objectName=theObjectName");
-            fail("missing domain should have caused failure");
-        } catch (ResolveEndpointFailedException e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-        }
+        ResolveEndpointFailedException e = assertThrows(ResolveEndpointFailedException.class,
+                () -> context.getEndpoint("jmx:platform?objectName=theObjectName"),
+                "missing domain should have caused failure");
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
     }
 
     @Test
     public void withoutObjectNameAndObjectProperties() {
-        try {
-            context.getEndpoint("jmx:platform?objectDomain=theObjectDomain");
-            fail("missing name should have caused failure");
-        } catch (ResolveEndpointFailedException e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-        }
+        ResolveEndpointFailedException e = assertThrows(ResolveEndpointFailedException.class,
+                () -> context.getEndpoint("jmx:platform?objectDomain=theObjectDomain"),
+                "missing name should have caused failure");
+        assertTrue(e.getCause() instanceof IllegalArgumentException);
     }
 }
diff --git a/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXEndpointTest.java b/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXEndpointTest.java
index a03e873b9be8..d00a2cd7bb51 100644
--- a/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXEndpointTest.java
+++ b/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXEndpointTest.java
@@ -28,8 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * Tests for the endpoint. Most of the params in the endpoint are set via the endpoint helper so there's no much beyond
@@ -48,13 +48,9 @@ public class JMXEndpointTest {
     public void setObjectNameThrowsWhenObjectPropertiesIsSet() {
         JMXEndpoint ep = new JMXEndpoint("urn:ignored", new JMXComponent());
         ep.setObjectProperties(new Hashtable<String, String>());
-        try {
-            // should fault since objectName is mutex with objectProperties
-            ep.setObjectName("foo");
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
+        assertThrows(IllegalArgumentException.class,
+                () -> ep.setObjectName("foo"),
+                "expected exception");
     }
 
     @Test
@@ -120,11 +116,9 @@ public class JMXEndpointTest {
     @Test
     public void noProducer() throws Exception {
         JMXEndpoint ep = context.getEndpoint("jmx:platform?objectDomain=FooDomain&key.name=theObjectName", JMXEndpoint.class);
-        try {
-            ep.createProducer();
-            fail("producer pattern is not supported");
-        } catch (UnsupportedOperationException e) {
-        }
+        assertThrows(UnsupportedOperationException.class,
+                () -> ep.createProducer(),
+                "producer pattern is not supported");
     }
 
     @Test
@@ -139,12 +133,10 @@ public class JMXEndpointTest {
     public void noObservedAttribute() throws Exception {
         JMXEndpoint ep = context.getEndpoint("jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=string",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_OBSERVED_ATTRIBUTE, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_OBSERVED_ATTRIBUTE, e.getMessage());
     }
 
     @Test
@@ -152,12 +144,10 @@ public class JMXEndpointTest {
         JMXEndpoint ep = context.getEndpoint(
                 "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=string&observedAttribute=foo",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_STRING_TO_COMPARE, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_STRING_TO_COMPARE, e.getMessage());
     }
 
     @Test
@@ -165,12 +155,10 @@ public class JMXEndpointTest {
         JMXEndpoint ep = context.getEndpoint(
                 "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=string&observedAttribute=foo&stringToCompare=foo",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_STRING_NOTIFY, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_STRING_NOTIFY, e.getMessage());
     }
 
     @Test
@@ -178,12 +166,10 @@ public class JMXEndpointTest {
         JMXEndpoint ep = context.getEndpoint(
                 "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=gauge&observedAttribute=foo",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_GAUGE_NOTIFY, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_GAUGE_NOTIFY, e.getMessage());
     }
 
     @Test
@@ -191,12 +177,10 @@ public class JMXEndpointTest {
         JMXEndpoint ep = context.getEndpoint(
                 "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=gauge&observedAttribute=foo&thresholdLow=100&notifyHigh=true",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_THRESHOLD_HIGH, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_THRESHOLD_HIGH, e.getMessage());
     }
 
     @Test
@@ -204,12 +188,10 @@ public class JMXEndpointTest {
         JMXEndpoint ep = context.getEndpoint(
                 "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=gauge&observedAttribute=foo&thresholdHigh=100&notifyHigh=true",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_THRESHOLD_LOW, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_THRESHOLD_LOW, e.getMessage());
     }
 
     @Test
@@ -217,11 +199,9 @@ public class JMXEndpointTest {
         JMXEndpoint ep = context.getEndpoint(
                 "jmx:service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi?objectDomain=FooDomain&key.name=theObjectName&monitorType=gauge",
                 JMXEndpoint.class);
-        try {
-            ep.createConsumer(null);
-            fail("expected exception");
-        } catch (IllegalArgumentException e) {
-            assertEquals(JMXEndpoint.ERR_PLATFORM_SERVER, e.getMessage());
-        }
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> ep.createConsumer(null),
+                "expected exception");
+        assertEquals(JMXEndpoint.ERR_PLATFORM_SERVER, e.getMessage());
     }
 }
diff --git a/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRobustRemoteConnectionTest.java b/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRobustRemoteConnectionTest.java
index 4ed29590f01d..860121a530ee 100644
--- a/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRobustRemoteConnectionTest.java
+++ b/components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRobustRemoteConnectionTest.java
@@ -32,8 +32,8 @@ import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * Test to verify:
@@ -91,13 +91,11 @@ public class JMXRobustRemoteConnectionTest extends SimpleBeanFixture {
     public void testRobustConnection() throws Exception {
 
         // the JMX service should not be started
-        try {
-            getSimpleMXBean().touch();
-            fail("The mxbean should not be available.");
-        } catch (Exception e) {
-            assertTrue(e instanceof java.lang.IllegalArgumentException);
-            assertEquals("Null connection", e.getMessage());
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> getSimpleMXBean().touch(),
+                "The mxbean should not be available.");
+        assertTrue(e instanceof java.lang.IllegalArgumentException);
+        assertEquals("Null connection", e.getMessage());
 
         // start the server;  the JMX consumer should connect and start;  the mock should receive a notification
         initServer();


(camel) 12/36: CAMEL-21196: modernize exception-based assertions in camel-olingo4

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit cf032e9a2026dad52b185f99f0c35756ef13f492
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:43:20 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-olingo4
---
 .../apache/camel/component/olingo4/Olingo4AppAPITest.java   | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/components/camel-olingo4/camel-olingo4-api/src/test/java/org/apache/camel/component/olingo4/Olingo4AppAPITest.java b/components/camel-olingo4/camel-olingo4-api/src/test/java/org/apache/camel/component/olingo4/Olingo4AppAPITest.java
index 5a7b0ed39bcc..b08d317fb3fb 100644
--- a/components/camel-olingo4/camel-olingo4-api/src/test/java/org/apache/camel/component/olingo4/Olingo4AppAPITest.java
+++ b/components/camel-olingo4/camel-olingo4-api/src/test/java/org/apache/camel/component/olingo4/Olingo4AppAPITest.java
@@ -80,6 +80,7 @@ import org.slf4j.LoggerFactory;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 
@@ -481,17 +482,15 @@ public class Olingo4AppAPITest {
         HttpStatusCode statusCode = statusHandler.await();
         LOG.info("Deletion of Entity was successful:  {}: {}", statusCode.getStatusCode(), statusCode.getInfo());
 
-        try {
-            LOG.info("Verify Delete Entity");
+        LOG.info("Verify Delete Entity");
 
-            entryHandler.reset();
-            olingoApp.read(edm, TEST_CREATE_PEOPLE, null, null, entryHandler);
+        entryHandler.reset();
+        olingoApp.read(edm, TEST_CREATE_PEOPLE, null, null, entryHandler);
 
+        assertThrows(Exception.class, () -> {
             entryHandler.await();
             fail("Entity not deleted!");
-        } catch (Exception e) {
-            LOG.info("Deleted entity not found: {}", e.getMessage());
-        }
+        });
     }
 
     @Test


(camel) 24/36: CAMEL-21196: modernize exception-based assertions in camel-hazelcast

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 1683285ee7cab84c9ba1475d44add205c63ccaf8
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:39:54 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-hazelcast
---
 .../hazelcast/HazelcastErrorMessagesTest.java      | 22 +++++++++-------------
 .../hazelcast/HazelcastSedaConfigurationTest.java  | 10 ++++------
 2 files changed, 13 insertions(+), 19 deletions(-)

diff --git a/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastErrorMessagesTest.java b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastErrorMessagesTest.java
index fd91d1196c2e..0eaa19609fdd 100644
--- a/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastErrorMessagesTest.java
+++ b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastErrorMessagesTest.java
@@ -19,8 +19,8 @@ package org.apache.camel.component.hazelcast;
 import org.apache.camel.builder.RouteBuilder;
 import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class HazelcastErrorMessagesTest extends HazelcastCamelTestSupport {
 
@@ -31,14 +31,12 @@ public class HazelcastErrorMessagesTest extends HazelcastCamelTestSupport {
                 from("hazelcast-atomicvalue:foo").to("seda:out");
             }
         };
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             context.addRoutes(builder);
             context.start();
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            assertTrue(e.getCause().getMessage()
-                    .contains("You cannot send messages to this endpoint: hazelcast-atomicvalue://foo"));
-        }
+        });
+        assertTrue(e.getCause().getMessage()
+                .contains("You cannot send messages to this endpoint: hazelcast-atomicvalue://foo"));
     }
 
     @Test
@@ -49,14 +47,12 @@ public class HazelcastErrorMessagesTest extends HazelcastCamelTestSupport {
             }
         };
 
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             context.addRoutes(builder);
             context.start();
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            assertTrue(
-                    e.getCause().getMessage().contains("You cannot send messages to this endpoint: hazelcast-instance://foo"));
-        }
+        });
+        assertTrue(
+                e.getCause().getMessage().contains("You cannot send messages to this endpoint: hazelcast-instance://foo"));
     }
 
     @Override
diff --git a/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaConfigurationTest.java b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaConfigurationTest.java
index 30d13fd77429..b1d43a68ccef 100644
--- a/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaConfigurationTest.java
+++ b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaConfigurationTest.java
@@ -25,8 +25,8 @@ import org.junit.jupiter.api.Test;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class HazelcastSedaConfigurationTest extends CamelTestSupport {
 
@@ -91,12 +91,10 @@ public class HazelcastSedaConfigurationTest extends CamelTestSupport {
 
     @Test
     public void createEndpointWithIllegalOnErrorDelayParam() throws Exception {
-        try {
+        ResolveEndpointFailedException e = assertThrows(ResolveEndpointFailedException.class, () -> {
             context.getEndpoint("hazelcast-seda:foo?onErrorDelay=-1");
-            fail("Should have thrown exception");
-        } catch (ResolveEndpointFailedException e) {
-            assertIsInstanceOf(PropertyBindingException.class, e.getCause());
-        }
+        });
+        assertIsInstanceOf(PropertyBindingException.class, e.getCause());
     }
 
 }


(camel) 32/36: CAMEL-21196: modernize exception-based assertions in camel-sql

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 5cf20290ab7eded276446b4c68702d7f844ffc19
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:47:56 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-sql
    
    Replace try-catch-fail patterns with assertThrows where applicable and convert
    fail() calls to throw new AssertionError() in test classes to use modern
    JUnit 5 exception testing approach, improving code clarity and consistency.
---
 .../sql/SqlProducerNamedParameterNotExistTest.java   | 20 +++++++-------------
 .../org/apache/camel/component/sql/SqlRouteTest.java |  3 +--
 .../sql/stored/ProducerBatchInvalidTest.java         | 19 ++++++++-----------
 .../jdbc/JdbcRemoveConfirmOrderAggregateTest.java    |  4 +---
 4 files changed, 17 insertions(+), 29 deletions(-)

diff --git a/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlProducerNamedParameterNotExistTest.java b/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlProducerNamedParameterNotExistTest.java
index 21be0fcd2f7b..679eb8521559 100644
--- a/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlProducerNamedParameterNotExistTest.java
+++ b/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlProducerNamedParameterNotExistTest.java
@@ -26,8 +26,8 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
 import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
 import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class SqlProducerNamedParameterNotExistTest extends CamelTestSupport {
 
@@ -56,22 +56,16 @@ public class SqlProducerNamedParameterNotExistTest extends CamelTestSupport {
         Map<String, Object> map = new HashMap<>();
         map.put("foo", "ASF");
 
-        try {
-            template.sendBody("direct:start", map);
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            assertTrue(e.getCause().getMessage().startsWith("Cannot find key [lic]"));
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> template.sendBody("direct:start", map));
+        assertTrue(e.getCause().getMessage().startsWith("Cannot find key [lic]"));
     }
 
     @Test
     public void testNamedParameterNotExistFromHeader() {
-        try {
-            template.sendBodyAndHeader("direct:start", "This is a dummy body", "foo", "ASF");
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            assertTrue(e.getCause().getMessage().startsWith("Cannot find key [lic]"));
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> template.sendBodyAndHeader("direct:start", "This is a dummy body", "foo", "ASF"));
+        assertTrue(e.getCause().getMessage().startsWith("Cannot find key [lic]"));
     }
 
     @Override
diff --git a/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlRouteTest.java b/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlRouteTest.java
index d66304e20433..a730e460d72a 100644
--- a/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlRouteTest.java
+++ b/components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlRouteTest.java
@@ -42,7 +42,6 @@ import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class SqlRouteTest extends CamelTestSupport {
 
@@ -176,7 +175,7 @@ public class SqlRouteTest extends CamelTestSupport {
             String projectName = jdbcTemplate.queryForObject("select project from projects where id = 10", String.class);
             assertEquals("test", projectName);
         } catch (EmptyResultDataAccessException e) {
-            fail("no row inserted");
+            throw new AssertionError("no row inserted", e);
         }
 
         Integer actualUpdateCount = mock.getExchanges().get(0).getIn().getHeader(SqlConstants.SQL_UPDATE_COUNT, Integer.class);
diff --git a/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java b/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java
index f08810513972..6e5cd3e6be66 100644
--- a/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java
+++ b/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java
@@ -29,7 +29,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class ProducerBatchInvalidTest extends CamelTestSupport {
 
@@ -69,16 +69,13 @@ public class ProducerBatchInvalidTest extends CamelTestSupport {
                 from("direct:query").to("sql-stored:BATCHFN(INTEGER :#num)?batch=true&batch=true").to("mock:query");
             }
         });
-        try {
-            context.start();
-            fail("Should throw exception");
-        } catch (FailedToCreateRouteException e) {
-            ResolveEndpointFailedException refe = assertIsInstanceOf(ResolveEndpointFailedException.class, e.getCause());
-            PropertyBindingException pbe = assertIsInstanceOf(PropertyBindingException.class, refe.getCause());
-            assertEquals("batch", pbe.getPropertyName());
-            assertIsInstanceOf(TypeConversionException.class, pbe.getCause());
-            assertEquals("[true, true]", pbe.getValue().toString());
-        }
+        FailedToCreateRouteException e = assertThrows(FailedToCreateRouteException.class,
+                () -> context.start());
+        ResolveEndpointFailedException refe = assertIsInstanceOf(ResolveEndpointFailedException.class, e.getCause());
+        PropertyBindingException pbe = assertIsInstanceOf(PropertyBindingException.class, refe.getCause());
+        assertEquals("batch", pbe.getPropertyName());
+        assertIsInstanceOf(TypeConversionException.class, pbe.getCause());
+        assertEquals("[true, true]", pbe.getValue().toString());
     }
 
 }
diff --git a/components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcRemoveConfirmOrderAggregateTest.java b/components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcRemoveConfirmOrderAggregateTest.java
index e3cca38a39e3..01a18da2517b 100644
--- a/components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcRemoveConfirmOrderAggregateTest.java
+++ b/components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcRemoveConfirmOrderAggregateTest.java
@@ -35,7 +35,6 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 import org.springframework.transaction.support.DefaultTransactionStatus;
 
 import static org.awaitility.Awaitility.await;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class JdbcRemoveConfirmOrderAggregateTest extends AbstractJdbcAggregationTestSupport {
 
@@ -111,8 +110,7 @@ public class JdbcRemoveConfirmOrderAggregateTest extends AbstractJdbcAggregation
                     .executeQuery("SELECT * FROM aggregationRepo1_completed");
             return !rs.next();
         } catch (SQLException e) {
-            fail(e);
-            return false;
+            throw new AssertionError(e);
         }
 
     }


(camel) 01/36: CAMEL-21196: modernize exception-based assertions in camel-avro

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit d259f6390e69089da42d01dfe8970fc47b743747
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:13:34 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-avro
    
    Convert try-catch-fail pattern to JUnit 5 assertThrows() in AvroMarshalAndUnmarshalTest.
---
 .../avro/AvroMarshalAndUnmarshalTest.java          |   9 +-
 .../bean/validator/BeanValidatorRouteTest.java     | 170 ++++++++++-----------
 2 files changed, 82 insertions(+), 97 deletions(-)

diff --git a/components/camel-avro/src/test/java/org/apache/camel/dataformat/avro/AvroMarshalAndUnmarshalTest.java b/components/camel-avro/src/test/java/org/apache/camel/dataformat/avro/AvroMarshalAndUnmarshalTest.java
index ea8b621d569c..8bf1ae160d14 100644
--- a/components/camel-avro/src/test/java/org/apache/camel/dataformat/avro/AvroMarshalAndUnmarshalTest.java
+++ b/components/camel-avro/src/test/java/org/apache/camel/dataformat/avro/AvroMarshalAndUnmarshalTest.java
@@ -25,7 +25,7 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class AvroMarshalAndUnmarshalTest extends CamelTestSupport {
 
@@ -46,7 +46,7 @@ public class AvroMarshalAndUnmarshalTest extends CamelTestSupport {
 
     @Test
     public void testMarshalAndUnmarshalWithDSL3() {
-        try {
+        assertThrows(Exception.class, () -> {
             context.addRoutes(new RouteBuilder() {
                 @Override
                 public void configure() {
@@ -54,10 +54,7 @@ public class AvroMarshalAndUnmarshalTest extends CamelTestSupport {
                             .to("mock:reverse");
                 }
             });
-            fail("Expect the exception here");
-        } catch (Exception ex) {
-            // expected
-        }
+        }, "Expect the exception here");
     }
 
     private void marshalAndUnmarshal(String inURI, String outURI) throws Exception {
diff --git a/components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/BeanValidatorRouteTest.java b/components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/BeanValidatorRouteTest.java
index aacc4b9ef798..e9068fe16a1b 100644
--- a/components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/BeanValidatorRouteTest.java
+++ b/components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/BeanValidatorRouteTest.java
@@ -39,7 +39,7 @@ import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.condition.OS.AIX;
 
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
@@ -90,22 +90,20 @@ class BeanValidatorRouteTest extends CamelTestSupport {
 
         final String url = "bean-validator://x";
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.requestBody(url, cars);
-            fail("should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(BeanValidationException.class, e.getCause());
-
-            BeanValidationException exception = (BeanValidationException) e.getCause();
-            Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
-
-            assertEquals(numberOfViolations, constraintViolations.size());
-            constraintViolations.forEach(cv -> {
-                assertEquals("licensePlate", cv.getPropertyPath().toString());
-                assertNull(cv.getInvalidValue());
-                assertEquals("must not be null", cv.getMessage());
-            });
-        }
+        });
+        assertIsInstanceOf(BeanValidationException.class, e.getCause());
+
+        BeanValidationException exception = (BeanValidationException) e.getCause();
+        Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
+
+        assertEquals(numberOfViolations, constraintViolations.size());
+        constraintViolations.forEach(cv -> {
+            assertEquals("licensePlate", cv.getPropertyPath().toString());
+            assertNull(cv.getInvalidValue());
+            assertEquals("must not be null", cv.getMessage());
+        });
 
         setLicensePlates(cars, "D-A");
 
@@ -124,22 +122,20 @@ class BeanValidatorRouteTest extends CamelTestSupport {
 
         final String url = "bean-validator://x?group=jakarta.validation.groups.Default";
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.requestBody(url, cars);
-            fail("should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(BeanValidationException.class, e.getCause());
-
-            BeanValidationException exception = (BeanValidationException) e.getCause();
-            Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
-
-            assertEquals(numberOfViolations, constraintViolations.size());
-            constraintViolations.forEach(cv -> {
-                assertEquals("licensePlate", cv.getPropertyPath().toString());
-                assertNull(cv.getInvalidValue());
-                assertEquals("must not be null", cv.getMessage());
-            });
-        }
+        });
+        assertIsInstanceOf(BeanValidationException.class, e.getCause());
+
+        BeanValidationException exception = (BeanValidationException) e.getCause();
+        Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
+
+        assertEquals(numberOfViolations, constraintViolations.size());
+        constraintViolations.forEach(cv -> {
+            assertEquals("licensePlate", cv.getPropertyPath().toString());
+            assertNull(cv.getInvalidValue());
+            assertEquals("must not be null", cv.getMessage());
+        });
 
         setLicensePlates(cars, "D-A");
 
@@ -158,22 +154,20 @@ class BeanValidatorRouteTest extends CamelTestSupport {
 
         final String url = "bean-validator://x?group=org.apache.camel.component.bean.validator.OptionalChecks";
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.requestBody(url, cars);
-            fail("should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(BeanValidationException.class, e.getCause());
-
-            BeanValidationException exception = (BeanValidationException) e.getCause();
-            Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
-
-            assertEquals(numberOfViolations, constraintViolations.size());
-            constraintViolations.forEach(cv -> {
-                assertEquals("licensePlate", cv.getPropertyPath().toString());
-                assertEquals("D-A", cv.getInvalidValue());
-                assertEquals("size must be between 5 and 14", cv.getMessage());
-            });
-        }
+        });
+        assertIsInstanceOf(BeanValidationException.class, e.getCause());
+
+        BeanValidationException exception = (BeanValidationException) e.getCause();
+        Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
+
+        assertEquals(numberOfViolations, constraintViolations.size());
+        constraintViolations.forEach(cv -> {
+            assertEquals("licensePlate", cv.getPropertyPath().toString());
+            assertEquals("D-A", cv.getInvalidValue());
+            assertEquals("size must be between 5 and 14", cv.getMessage());
+        });
 
         setLicensePlates(cars, "DD-AB-123");
 
@@ -192,41 +186,37 @@ class BeanValidatorRouteTest extends CamelTestSupport {
 
         final String url = "bean-validator://x?group=org.apache.camel.component.bean.validator.OrderedChecks";
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.requestBody(url, cars);
-            fail("should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(BeanValidationException.class, e.getCause());
-
-            BeanValidationException exception = (BeanValidationException) e.getCause();
-            Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
-
-            assertEquals(numberOfViolations, constraintViolations.size());
-            constraintViolations.forEach(cv -> {
-                assertEquals("manufacturer", cv.getPropertyPath().toString());
-                assertNull(cv.getInvalidValue());
-                assertEquals("must not be null", cv.getMessage());
-            });
-        }
+        });
+        assertIsInstanceOf(BeanValidationException.class, e.getCause());
+
+        BeanValidationException exception = (BeanValidationException) e.getCause();
+        Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
+
+        assertEquals(numberOfViolations, constraintViolations.size());
+        constraintViolations.forEach(cv -> {
+            assertEquals("manufacturer", cv.getPropertyPath().toString());
+            assertNull(cv.getInvalidValue());
+            assertEquals("must not be null", cv.getMessage());
+        });
 
         setManufacturer(cars, "BMW");
 
-        try {
+        CamelExecutionException e2 = assertThrows(CamelExecutionException.class, () -> {
             template.requestBody(url, cars);
-            fail("should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(BeanValidationException.class, e.getCause());
-
-            BeanValidationException exception = (BeanValidationException) e.getCause();
-            Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
-
-            assertEquals(numberOfViolations, constraintViolations.size());
-            constraintViolations.forEach(cv -> {
-                assertEquals("licensePlate", cv.getPropertyPath().toString());
-                assertEquals("D-A", cv.getInvalidValue());
-                assertEquals("size must be between 5 and 14", cv.getMessage());
-            });
-        }
+        });
+        assertIsInstanceOf(BeanValidationException.class, e2.getCause());
+
+        BeanValidationException exception2 = (BeanValidationException) e2.getCause();
+        Set<ConstraintViolation<Object>> constraintViolations2 = exception2.getConstraintViolations();
+
+        assertEquals(numberOfViolations, constraintViolations2.size());
+        constraintViolations2.forEach(cv -> {
+            assertEquals("licensePlate", cv.getPropertyPath().toString());
+            assertEquals("D-A", cv.getInvalidValue());
+            assertEquals("size must be between 5 and 14", cv.getMessage());
+        });
 
         setLicensePlates(cars, "DD-AB-123");
 
@@ -260,22 +250,20 @@ class BeanValidatorRouteTest extends CamelTestSupport {
 
         final String url = "bean-validator://x";
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.requestBody(url, cars);
-            fail("should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(BeanValidationException.class, e.getCause());
-
-            BeanValidationException exception = (BeanValidationException) e.getCause();
-            Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
-
-            assertEquals(numberOfViolations, constraintViolations.size());
-            constraintViolations.forEach(cv -> {
-                assertEquals("licensePlate", cv.getPropertyPath().toString());
-                assertEquals("D-A", cv.getInvalidValue());
-                assertEquals("size must be between 5 and 14", cv.getMessage());
-            });
-        }
+        });
+        assertIsInstanceOf(BeanValidationException.class, e.getCause());
+
+        BeanValidationException exception = (BeanValidationException) e.getCause();
+        Set<ConstraintViolation<Object>> constraintViolations = exception.getConstraintViolations();
+
+        assertEquals(numberOfViolations, constraintViolations.size());
+        constraintViolations.forEach(cv -> {
+            assertEquals("licensePlate", cv.getPropertyPath().toString());
+            assertEquals("D-A", cv.getInvalidValue());
+            assertEquals("size must be between 5 and 14", cv.getMessage());
+        });
     }
 
     Car createCar(String manufacturer, String licencePlate) {


(camel) 31/36: CAMEL-21196: modernize exception-based assertions in camel-workday

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit a7109a345b2657cbad3fb0289e1f0d83e897a375
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:47:53 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-workday
    
    Replace try-catch-fail patterns with assertThrows in:
    - WorkdayCommonAPIProducerTest.java (2 occurrences)
    - WorkdayReportProducerTest.java (1 occurrence)
---
 .../apache/camel/WorkdayCommonAPIProducerTest.java | 27 +++++-----------------
 .../apache/camel/WorkdayReportProducerTest.java    | 15 ++++--------
 2 files changed, 10 insertions(+), 32 deletions(-)

diff --git a/components/camel-workday/src/test/java/org/apache/camel/WorkdayCommonAPIProducerTest.java b/components/camel-workday/src/test/java/org/apache/camel/WorkdayCommonAPIProducerTest.java
index 6c32f8595d8e..acc33c4b22c4 100644
--- a/components/camel-workday/src/test/java/org/apache/camel/WorkdayCommonAPIProducerTest.java
+++ b/components/camel-workday/src/test/java/org/apache/camel/WorkdayCommonAPIProducerTest.java
@@ -27,7 +27,6 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class WorkdayCommonAPIProducerTest extends CamelTestSupport {
 
@@ -56,21 +55,14 @@ public class WorkdayCommonAPIProducerTest extends CamelTestSupport {
     public void createProducerNoHostConfiguration() {
         WorkdayComponent workdayComponent = context.getComponent("workday", WorkdayComponent.class);
 
-        try {
-
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
             WorkdayEndpoint workdayEndpoint = (WorkdayEndpoint) workdayComponent
                     .createEndpoint(
                             "workday:commonAPI:/workers?" + "tenant=camel" + "&clientId=f7014d38-99d2-4969-b740-b5b62db6b46a"
                                     + "&clientSecret=7dbaf280-3cea-11ea-b77f-2e728ce88125" + "&tokenRefresh=88689ab63cda"
                                     + "&format=json");
-        } catch (Exception exception) {
-
-            assertEquals(exception.getClass(), IllegalArgumentException.class);
-            assertEquals("Host must be specified", exception.getMessage());
-            return;
-        }
-
-        fail("Required parameters validation failed.");
+        });
+        assertEquals("Host must be specified", exception.getMessage());
     }
 
     @Test
@@ -85,17 +77,10 @@ public class WorkdayCommonAPIProducerTest extends CamelTestSupport {
 
         WorkdayCommonAPIProducer workdayProducer = new WorkdayCommonAPIProducer(workdayEndpoint);
 
-        try {
-
+        Exception exception = assertThrows(MalformedURLException.class, () -> {
             String workdayUri = workdayProducer.prepareUri(workdayEndpoint.getWorkdayConfiguration());
-        } catch (Exception exception) {
-
-            assertEquals(exception.getClass(), MalformedURLException.class);
-            assertEquals("An invalid Workday Common endpoint: '/worker' was provided.", exception.getMessage());
-            return;
-        }
-
-        fail("Required parameters validation failed.");
+        });
+        assertEquals("An invalid Workday Common endpoint: '/worker' was provided.", exception.getMessage());
     }
 
     @Test
diff --git a/components/camel-workday/src/test/java/org/apache/camel/WorkdayReportProducerTest.java b/components/camel-workday/src/test/java/org/apache/camel/WorkdayReportProducerTest.java
index 9f11ab4cc0de..0e8a62e384b2 100644
--- a/components/camel-workday/src/test/java/org/apache/camel/WorkdayReportProducerTest.java
+++ b/components/camel-workday/src/test/java/org/apache/camel/WorkdayReportProducerTest.java
@@ -24,7 +24,7 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class WorkdayReportProducerTest extends CamelTestSupport {
 
@@ -53,21 +53,14 @@ public class WorkdayReportProducerTest extends CamelTestSupport {
     public void createProducerNoHostConfiguration() {
         WorkdayComponent workdayComponent = context.getComponent("workday", WorkdayComponent.class);
 
-        try {
-
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
             WorkdayEndpoint workdayEndpoint = (WorkdayEndpoint) workdayComponent
                     .createEndpoint("workday:report:/ISU_Camel/Custom_Report_Employees?" + "tenant=camel"
                                     + "&clientId=f7014d38-99d2-4969-b740-b5b62db6b46a"
                                     + "&clientSecret=7dbaf280-3cea-11ea-b77f-2e728ce88125" + "&tokenRefresh=88689ab63cda"
                                     + "&format=json");
-        } catch (Exception exception) {
-
-            assertEquals(IllegalArgumentException.class, exception.getClass());
-            assertEquals("Host must be specified", exception.getMessage());
-            return;
-        }
-
-        fail("Required parameters validation failed.");
+        });
+        assertEquals("Host must be specified", exception.getMessage());
     }
 
     @Test


(camel) 23/36: CAMEL-21196: modernize exception-based assertions in camel-guava-eventbus

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit c9639f77466ddfc62969bec2557a07556953f7cd
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:39:52 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-guava-eventbus
---
 .../eventbus/GuavaEventBusConsumerConfigurationTest.java     | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/components/camel-guava-eventbus/src/test/java/org/apache/camel/component/guava/eventbus/GuavaEventBusConsumerConfigurationTest.java b/components/camel-guava-eventbus/src/test/java/org/apache/camel/component/guava/eventbus/GuavaEventBusConsumerConfigurationTest.java
index b477f4d90f10..f3149d297f7e 100644
--- a/components/camel-guava-eventbus/src/test/java/org/apache/camel/component/guava/eventbus/GuavaEventBusConsumerConfigurationTest.java
+++ b/components/camel-guava-eventbus/src/test/java/org/apache/camel/component/guava/eventbus/GuavaEventBusConsumerConfigurationTest.java
@@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class GuavaEventBusConsumerConfigurationTest extends CamelTestSupport {
 
@@ -49,13 +49,11 @@ public class GuavaEventBusConsumerConfigurationTest extends CamelTestSupport {
             }
         });
 
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             context.start();
-            fail("Should throw exception");
-        } catch (Exception e) {
-            IllegalStateException ise = assertIsInstanceOf(IllegalStateException.class, e.getCause());
-            assertEquals("You cannot set both 'eventClass' and 'listenerInterface' parameters.", ise.getMessage());
-        }
+        });
+        IllegalStateException ise = assertIsInstanceOf(IllegalStateException.class, e.getCause());
+        assertEquals("You cannot set both 'eventClass' and 'listenerInterface' parameters.", ise.getMessage());
     }
 
 }


(camel) 36/36: CAMEL-21196: modernize exception-based assertions in camel-clickup

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 0d793d3964c3858852d39cd689ee7a497b9eccc9
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 20:02:46 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-clickup
    
    Replace fail(e) pattern with throw new AssertionError for modernized exception handling.
---
 .../apache/camel/component/clickup/ClickUpWebhookRegistrationTest.java  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/components/camel-clickup/src/test/java/org/apache/camel/component/clickup/ClickUpWebhookRegistrationTest.java b/components/camel-clickup/src/test/java/org/apache/camel/component/clickup/ClickUpWebhookRegistrationTest.java
index 6c96994c3044..961ce9d32b92 100644
--- a/components/camel-clickup/src/test/java/org/apache/camel/component/clickup/ClickUpWebhookRegistrationTest.java
+++ b/components/camel-clickup/src/test/java/org/apache/camel/component/clickup/ClickUpWebhookRegistrationTest.java
@@ -81,7 +81,7 @@ public class ClickUpWebhookRegistrationTest extends ClickUpTestSupport {
 
                 assertInstanceOf(WebhookCreationCommand.class, command);
             } catch (IOException e) {
-                fail(e);
+                throw new AssertionError("Failed to parse recorded message", e);
             }
 
             mockProcessor.clearRecordedMessages();


(camel) 04/36: CAMEL-21196: modernize exception-based assertions in camel-graphql

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit f5b495a23c7a42804e5542008cd5e53ee890ee72
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:17:48 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-graphql
    
    Replace try-catch-fail pattern with JUnit 5 assertThrows() in
    GraphqlComponentTest.checkThrowException() test method. Updated
    imports to use assertThrows instead of fail.
---
 ...indySimpleCsvMandatoryFieldsUnmarshallTest.java | 19 +++--------
 .../BindyFixedLengthDelimitedFieldTest.java        | 38 ++++++++--------------
 .../dynamic/BindyFixedLengthDynamicFieldTest.java  | 14 +++-----
 .../component/graphql/GraphqlComponentTest.java    | 15 ++++-----
 4 files changed, 29 insertions(+), 57 deletions(-)

diff --git a/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvMandatoryFieldsUnmarshallTest.java b/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvMandatoryFieldsUnmarshallTest.java
index c8d09388887e..f41a8bd942e8 100644
--- a/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvMandatoryFieldsUnmarshallTest.java
+++ b/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvMandatoryFieldsUnmarshallTest.java
@@ -26,9 +26,8 @@ import org.apache.camel.test.spring.junit5.CamelSpringTest;
 import org.junit.jupiter.api.Test;
 import org.springframework.test.annotation.DirtiesContext;
 import org.springframework.test.context.ContextConfiguration;
-import org.springframework.util.Assert;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 @ContextConfiguration
 @CamelSpringTest
@@ -65,13 +64,9 @@ public class BindySimpleCsvMandatoryFieldsUnmarshallTest {
 
         resultEndpoint1.expectedMessageCount(0);
 
-        try {
+        assertThrows(CamelExecutionException.class, () -> {
             template1.sendBody(record1);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            Assert.isInstanceOf(Exception.class, e.getCause());
-            // log.info(">> Error : " + e);
-        }
+        });
 
         resultEndpoint1.assertIsSatisfied();
     }
@@ -126,13 +121,9 @@ public class BindySimpleCsvMandatoryFieldsUnmarshallTest {
 
         resultEndpoint1.expectedMessageCount(0);
 
-        try {
+        assertThrows(CamelExecutionException.class, () -> {
             template1.sendBody(record6);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            // expected
-            Assert.isInstanceOf(IllegalArgumentException.class, e.getCause());
-        }
+        });
 
         resultEndpoint1.assertIsSatisfied();
     }
diff --git a/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/delimited/BindyFixedLengthDelimitedFieldTest.java b/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/delimited/BindyFixedLengthDelimitedFieldTest.java
index fe935de07809..780c03838d90 100644
--- a/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/delimited/BindyFixedLengthDelimitedFieldTest.java
+++ b/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/delimited/BindyFixedLengthDelimitedFieldTest.java
@@ -33,8 +33,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This test validates the marshalling / unmarshalling of delimited, variable-length fields within a 'fixed-length'
@@ -85,15 +85,11 @@ public class BindyFixedLengthDelimitedFieldTest extends CamelTestSupport {
 
         unmarshallResult.reset();
         unmarshallResult.expectedMessageCount(0);
-        try {
+        Exception exception = assertThrows(Exception.class, () -> {
             template.sendBody(URI_DIRECT_UNMARSHALL, TEST_RECORD_WITH_EXTRA_CHARS);
-        } catch (Exception e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-            assertTrue(e.getCause().getMessage().contains("unmapped characters"));
-            return;
-        }
-
-        fail("An error is expected when unmapped characters are encountered in the fixed length record");
+        });
+        assertTrue(exception.getCause() instanceof IllegalArgumentException);
+        assertTrue(exception.getCause().getMessage().contains("unmapped characters"));
     }
 
     @Test
@@ -101,15 +97,11 @@ public class BindyFixedLengthDelimitedFieldTest extends CamelTestSupport {
 
         unmarshallResult.reset();
         unmarshallResult.expectedMessageCount(0);
-        try {
+        Exception exception = assertThrows(Exception.class, () -> {
             template.sendBody(URI_DIRECT_UNMARSHALL, TEST_RECORD_WITH_WHITSPACE_THEN_EXTRA_CHAR);
-        } catch (Exception e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-            assertTrue(e.getCause().getMessage().contains("unmapped characters"));
-            return;
-        }
-
-        fail("An error is expected when unmapped characters are encountered in the fixed length record");
+        });
+        assertTrue(exception.getCause() instanceof IllegalArgumentException);
+        assertTrue(exception.getCause().getMessage().contains("unmapped characters"));
     }
 
     @Test
@@ -117,15 +109,11 @@ public class BindyFixedLengthDelimitedFieldTest extends CamelTestSupport {
 
         unmarshallResult.reset();
         unmarshallResult.expectedMessageCount(0);
-        try {
+        Exception exception = assertThrows(Exception.class, () -> {
             template.sendBody(URI_DIRECT_UNMARSHALL, TEST_RECORD_WITH_SINGLE_EXTRA_CHAR);
-        } catch (Exception e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-            assertTrue(e.getCause().getMessage().contains("unmapped characters"));
-            return;
-        }
-
-        fail("An error is expected when unmapped characters are encountered in the fixed length record");
+        });
+        assertTrue(exception.getCause() instanceof IllegalArgumentException);
+        assertTrue(exception.getCause().getMessage().contains("unmapped characters"));
     }
 
     @Test
diff --git a/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/dynamic/BindyFixedLengthDynamicFieldTest.java b/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/dynamic/BindyFixedLengthDynamicFieldTest.java
index e45f93763482..9bee5f327f06 100644
--- a/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/dynamic/BindyFixedLengthDynamicFieldTest.java
+++ b/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/dynamic/BindyFixedLengthDynamicFieldTest.java
@@ -33,8 +33,8 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This test validates the marshalling / unmarshalling of a fixed-length data field for which the length of the field is
@@ -84,15 +84,11 @@ public class BindyFixedLengthDynamicFieldTest extends CamelTestSupport {
 
         unmarshallResult.reset();
         unmarshallResult.expectedMessageCount(0);
-        try {
+        Exception exception = assertThrows(Exception.class, () -> {
             template.sendBody(URI_DIRECT_UNMARSHALL, TEST_RECORD_WITH_EXTRA_CHARS);
-        } catch (Exception e) {
-            assertTrue(e.getCause() instanceof IllegalArgumentException);
-            assertTrue(e.getCause().getMessage().contains("unmapped characters"));
-            return;
-        }
-
-        fail("An error is expected when unmapped characters are encountered in the fixed length record");
+        });
+        assertTrue(exception.getCause() instanceof IllegalArgumentException);
+        assertTrue(exception.getCause().getMessage().contains("unmapped characters"));
     }
 
     @Test
diff --git a/components/camel-graphql/src/test/java/org/apache/camel/component/graphql/GraphqlComponentTest.java b/components/camel-graphql/src/test/java/org/apache/camel/component/graphql/GraphqlComponentTest.java
index 96459894721d..cc9bc7b325a0 100644
--- a/components/camel-graphql/src/test/java/org/apache/camel/component/graphql/GraphqlComponentTest.java
+++ b/components/camel-graphql/src/test/java/org/apache/camel/component/graphql/GraphqlComponentTest.java
@@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class GraphqlComponentTest extends CamelTestSupport {
 
@@ -244,14 +244,11 @@ public class GraphqlComponentTest extends CamelTestSupport {
     public void checkThrowException() throws Exception {
         result.expectedMessageCount(0);
 
-        try {
-            template.sendBodyAndHeader("direct:start9", "", "kaboom", "force some error");
-            fail();
-        } catch (Exception e) {
-            HttpOperationFailedException he = assertInstanceOf(HttpOperationFailedException.class, e.getCause());
-            assertEquals(500, he.getStatusCode());
-            assertEquals("Forced error due to kaboom", he.getHttpResponseStatus());
-        }
+        Exception e = assertThrows(Exception.class,
+                () -> template.sendBodyAndHeader("direct:start9", "", "kaboom", "force some error"));
+        HttpOperationFailedException he = assertInstanceOf(HttpOperationFailedException.class, e.getCause());
+        assertEquals(500, he.getStatusCode());
+        assertEquals("Forced error due to kaboom", he.getHttpResponseStatus());
 
         result.assertIsSatisfied();
     }


(camel) 03/36: CAMEL-21196: modernize exception-based assertions in camel-groovy

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 562ff5de80899697dce02c4a10bf95b8dfdbbb49
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:17:24 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-groovy
    
    Convert try-catch-fail patterns to modern JUnit 5 assertThrows() in test files:
    - GroovyLanguageTest.java
    - GroovyExpressionTest.java
    - GroovyLogEipTest.java
    
    Updated imports to replace fail with assertThrows for better readability and
    modern testing patterns.
---
 .../apache/camel/language/groovy/GroovyExpressionTest.java | 14 ++++++--------
 .../apache/camel/language/groovy/GroovyLanguageTest.java   | 12 +++++-------
 .../apache/camel/processor/groovy/GroovyLogEipTest.java    | 10 ++++------
 3 files changed, 15 insertions(+), 21 deletions(-)

diff --git a/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyExpressionTest.java b/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyExpressionTest.java
index 946d1b90fec1..ecd8fa9d8d23 100644
--- a/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyExpressionTest.java
+++ b/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyExpressionTest.java
@@ -28,8 +28,8 @@ import static org.apache.camel.test.junit5.TestSupport.assertExpression;
 import static org.apache.camel.test.junit5.TestSupport.assertInMessageHeader;
 import static org.apache.camel.test.junit5.TestSupport.assertPredicate;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class GroovyExpressionTest {
     private static final Logger LOG = LoggerFactory.getLogger(GroovyExpressionTest.class);
@@ -104,14 +104,12 @@ public class GroovyExpressionTest {
 
     @Test
     public void testInvalidExpressionFailsWithMeaningfulException() {
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             GroovyLanguage.groovy("exchange.doesNotExist").evaluate(exchange);
-            fail("This test case should have thrown an exception!");
-        } catch (Exception e) {
-            LOG.debug("Caught expected exception: {}", e.getMessage(), e);
-            String message = e.getMessage();
-            assertTrue(message.contains("doesNotExist"), "The message should include 'doesNotExist' but was: " + message);
-        }
+        });
+        LOG.debug("Caught expected exception: {}", e.getMessage(), e);
+        String message = e.getMessage();
+        assertTrue(message.contains("doesNotExist"), "The message should include 'doesNotExist' but was: " + message);
     }
 
     @BeforeEach
diff --git a/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyLanguageTest.java b/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyLanguageTest.java
index 2c12a0dabed1..b49b2dda0750 100644
--- a/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyLanguageTest.java
+++ b/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyLanguageTest.java
@@ -29,8 +29,8 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class GroovyLanguageTest extends LanguageTestSupport {
 
@@ -65,16 +65,14 @@ public class GroovyLanguageTest extends LanguageTestSupport {
             assertTrue(g.validateExpression("exchange.getExchangeId()"));
             assertTrue(g.validatePredicate("2 * 3 > 4"));
 
-            try {
+            GroovyValidationException e = assertThrows(GroovyValidationException.class, () -> {
                 g.validateExpression("""
                         var a = 123;
                         println a */ 2;
                         """);
-                fail("Should throw error");
-            } catch (GroovyValidationException e) {
-                assertEquals(23, e.getIndex());
-                assertInstanceOf(MultipleCompilationErrorsException.class, e.getCause());
-            }
+            });
+            assertEquals(23, e.getIndex());
+            assertInstanceOf(MultipleCompilationErrorsException.class, e.getCause());
         }
     }
 
diff --git a/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java b/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java
index 6a02b09d64a8..8f21b2a21477 100644
--- a/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java
+++ b/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java
@@ -25,7 +25,7 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class GroovyLogEipTest extends CamelTestSupport {
 
@@ -43,12 +43,10 @@ public class GroovyLogEipTest extends CamelTestSupport {
 
     @Test
     public void testLogFail() {
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             template.sendBody("direct:fail", 4);
-            fail("Should fail");
-        } catch (Exception e) {
-            Assertions.assertInstanceOf(MissingPropertyException.class, e.getCause());
-        }
+        });
+        Assertions.assertInstanceOf(MissingPropertyException.class, e.getCause());
     }
 
     @Override


(camel) 33/36: CAMEL-21196: modernize exception-based assertions in camel-xslt-saxon

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 5232cd3388a1ce2aed0613b3593503afbfc27154
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:48:44 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-xslt-saxon
    
    Replace try-catch-fail patterns with assertThrows in:
    - SaxonXsltFeatureRouteTest.java (1 occurrence)
    - SaxonInvalidXsltFileTest.java (1 occurrence)
---
 .../camel/component/xslt/SaxonInvalidXsltFileTest.java    | 13 +++++--------
 .../camel/component/xslt/SaxonXsltFeatureRouteTest.java   | 15 ++++++---------
 2 files changed, 11 insertions(+), 17 deletions(-)

diff --git a/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonInvalidXsltFileTest.java b/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonInvalidXsltFileTest.java
index 6dff1db2d2dd..e3c1dc7a38f6 100644
--- a/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonInvalidXsltFileTest.java
+++ b/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonInvalidXsltFileTest.java
@@ -24,24 +24,21 @@ import org.apache.camel.impl.DefaultCamelContext;
 import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class SaxonInvalidXsltFileTest {
 
     @Test
     public void testInvalidStylesheet() {
-        try {
+        Exception e = assertThrows(Exception.class, () -> {
             RouteBuilder builder = createRouteBuilder();
             try (CamelContext context = new DefaultCamelContext()) {
                 context.addRoutes(builder);
                 context.start();
-
-                fail("Should have thrown an exception due XSL compilation error");
             }
-        } catch (Exception e) {
-            // expected
-            assertIsInstanceOf(TransformerException.class, e.getCause().getCause().getCause());
-        }
+        });
+        // expected
+        assertIsInstanceOf(TransformerException.class, e.getCause().getCause().getCause());
     }
 
     protected RouteBuilder createRouteBuilder() {
diff --git a/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonXsltFeatureRouteTest.java b/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonXsltFeatureRouteTest.java
index 99bb8526ee9a..248e0a83a6f8 100644
--- a/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonXsltFeatureRouteTest.java
+++ b/components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonXsltFeatureRouteTest.java
@@ -22,8 +22,8 @@ import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class SaxonXsltFeatureRouteTest extends CamelTestSupport {
 
@@ -35,15 +35,12 @@ public class SaxonXsltFeatureRouteTest extends CamelTestSupport {
     }
 
     public void sendXmlMessage(String uri, String message) {
-        try {
+        Exception ex = assertThrows(Exception.class, () -> {
             template.sendBody("direct:start1", message);
-            fail("expect an exception here");
-        } catch (Exception ex) {
-            // expect an exception here
-            assertTrue(ex instanceof CamelExecutionException, "Get a wrong exception");
-            assertTrue(ex.getCause() instanceof XPathException, "Get a wrong exception cause");
-        }
-
+        });
+        // expect an exception here
+        assertTrue(ex instanceof CamelExecutionException, "Get a wrong exception");
+        assertTrue(ex.getCause() instanceof XPathException, "Get a wrong exception cause");
     }
 
     @Override


(camel) 18/36: CAMEL-21196: modernize exception-based assertions in camel-jdbc

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit fa4eba3ff2c1a4487749c267696a8cb6006f5b1a
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:21:29 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jdbc
    
    Replace try-catch-fail pattern with assertThrows in JdbcOptionsTest.
---
 .../org/apache/camel/component/jdbc/JdbcOptionsTest.java   | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcOptionsTest.java b/components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcOptionsTest.java
index 63cf430d9599..ab20a459e3fb 100644
--- a/components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcOptionsTest.java
+++ b/components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcOptionsTest.java
@@ -27,8 +27,8 @@ import org.apache.camel.component.mock.MockEndpoint;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class JdbcOptionsTest extends AbstractJdbcTestSupport {
 
@@ -76,13 +76,11 @@ public class JdbcOptionsTest extends AbstractJdbcTestSupport {
 
     @Test
     public void testNoDataSourceInRegistry() {
-        try {
-            template.sendBody("jdbc:xxx", "Hello World");
-            fail("Should have thrown a ResolveEndpointFailedException");
-        } catch (ResolveEndpointFailedException e) {
-            assertEquals("No bean could be found in the registry for: xxx of type: javax.sql.DataSource",
-                    e.getCause().getMessage());
-        }
+        ResolveEndpointFailedException e = assertThrows(ResolveEndpointFailedException.class,
+                () -> template.sendBody("jdbc:xxx", "Hello World"),
+                "Should have thrown a ResolveEndpointFailedException");
+        assertEquals("No bean could be found in the registry for: xxx of type: javax.sql.DataSource",
+                e.getCause().getMessage());
     }
 
     @Test


(camel) 02/36: CAMEL-21196: modernize exception-based assertions in camel-exec

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 95c697b9ca6f483ae3a2fb8df4896936bfdc484c
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:15:55 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-exec
    
    Replace JUnit 3 style fail() call with modern JUnit 5 assertTrue()
    assertion with error message in ExecJava8IssueTest.
    
    Changes:
    - Updated import from Assertions.fail to Assertions.assertTrue
    - Converted fail("message") to assertTrue(condition, "message")
---
 .../java/org/apache/camel/component/exec/ExecJava8IssueTest.java    | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/components/camel-exec/src/test/java/org/apache/camel/component/exec/ExecJava8IssueTest.java b/components/camel-exec/src/test/java/org/apache/camel/component/exec/ExecJava8IssueTest.java
index 30bdfa790ec5..415c1f3c808a 100644
--- a/components/camel-exec/src/test/java/org/apache/camel/component/exec/ExecJava8IssueTest.java
+++ b/components/camel-exec/src/test/java/org/apache/camel/component/exec/ExecJava8IssueTest.java
@@ -37,7 +37,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Test to duplicate issues with Camel's exec command in Java 8 on Unix This issue appears to be caused by a race
@@ -54,9 +54,7 @@ public class ExecJava8IssueTest {
     @BeforeEach
     public void setUp() {
         tempDir = new File("target", tempDirName);
-        if (!(tempDir.mkdir())) {
-            fail("Couldn't create temp dir for test");
-        }
+        assertTrue(tempDir.mkdir(), "Couldn't create temp dir for test");
     }
 
     @AfterEach


(camel) 14/36: CAMEL-21196: modernize exception-based assertions in camel-sjms

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 76e93723e6d05374581f1f632f35bd195bb3e617
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:45:47 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-sjms
---
 .../component/sjms/producer/QueueProducerQoSTest.java      | 14 ++++++--------
 .../sjms/tx/TransactedQueueInOutProducerTest.java          | 10 ++++------
 .../component/sjms/tx/TransactedQueueProducerTest.java     | 10 ++++------
 .../component/sjms/tx/TransactedTopicProducerTest.java     | 10 ++++------
 4 files changed, 18 insertions(+), 26 deletions(-)

diff --git a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/producer/QueueProducerQoSTest.java b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/producer/QueueProducerQoSTest.java
index f951d7205239..493b479301eb 100644
--- a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/producer/QueueProducerQoSTest.java
+++ b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/producer/QueueProducerQoSTest.java
@@ -35,7 +35,7 @@ import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.RegisterExtension;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class QueueProducerQoSTest extends CamelTestSupport {
 
@@ -82,14 +82,12 @@ public class QueueProducerQoSTest extends CamelTestSupport {
         String endpoint = String.format("sjms:queue:%s?timeToLive=1000&exchangePattern=InOut&requestTimeout=500",
                 TEST_INOUT_DESTINATION_NAME);
 
-        try {
+        // we are expecting an exception here because there are no consumers on this queue,
+        // so we will not be able to do a real InOut/request-response, but that's okay
+        // we're just interested in the message becoming expired
+        assertThrows(Exception.class, () -> {
             template.requestBody(endpoint, "test message");
-            fail("we aren't expecting any consumers, so should not succeed");
-        } catch (Exception e) {
-            // we are expecting an exception here because there are no consumers on this queue,
-            // so we will not be able to do a real InOut/request-response, but that's okay
-            // we're just interested in the message becoming expired
-        }
+        });
 
         MockEndpoint.assertIsSatisfied(context);
 
diff --git a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueInOutProducerTest.java b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueInOutProducerTest.java
index 603ad4d6b61c..ab37ba3be1ad 100644
--- a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueInOutProducerTest.java
+++ b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueInOutProducerTest.java
@@ -33,7 +33,7 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.RegisterExtension;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class TransactedQueueInOutProducerTest extends CamelTestSupport {
 
@@ -48,12 +48,10 @@ public class TransactedQueueInOutProducerTest extends CamelTestSupport {
         getMockEndpoint("mock:result").expectedBodiesReceived("Hello World 2");
         getMockEndpoint("mock:result2").expectedBodiesReceived("Changed Hello World 2");
 
-        try {
+        // expected
+        assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("direct:start", "Hello World 1", "isfailed", true);
-            fail("Should fail");
-        } catch (Exception e) {
-            // expected
-        }
+        });
         template.sendBodyAndHeader("direct:start", "Hello World 2", "isfailed", false);
 
         MockEndpoint.assertIsSatisfied(context);
diff --git a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueProducerTest.java b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueProducerTest.java
index dada924b4601..968ee05ed600 100644
--- a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueProducerTest.java
+++ b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedQueueProducerTest.java
@@ -32,7 +32,7 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.RegisterExtension;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class TransactedQueueProducerTest extends CamelTestSupport {
 
@@ -47,12 +47,10 @@ public class TransactedQueueProducerTest extends CamelTestSupport {
         getMockEndpoint("mock:result").expectedBodiesReceived("Hello World 2");
         getMockEndpoint("mock:result2").expectedBodiesReceived("Hello World 2");
 
-        try {
+        // expected
+        assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("direct:start", "Hello World 1", "isfailed", true);
-            fail("Should fail");
-        } catch (Exception e) {
-            // expected
-        }
+        });
         template.sendBodyAndHeader("direct:start", "Hello World 2", "isfailed", false);
 
         MockEndpoint.assertIsSatisfied(context);
diff --git a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedTopicProducerTest.java b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedTopicProducerTest.java
index 6a8f7afd0d70..7e4f8ccbc47e 100644
--- a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedTopicProducerTest.java
+++ b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/tx/TransactedTopicProducerTest.java
@@ -28,7 +28,7 @@ import org.apache.camel.component.sjms.SjmsComponent;
 import org.apache.camel.component.sjms.support.JmsTestSupport;
 import org.junit.jupiter.api.Test;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class TransactedTopicProducerTest extends JmsTestSupport {
 
@@ -45,12 +45,10 @@ public class TransactedTopicProducerTest extends JmsTestSupport {
         MockEndpoint mock = getMockEndpoint("mock:result");
         mock.expectedBodiesReceived("Hello World 2");
 
-        try {
+        // expected
+        assertThrows(Exception.class, () -> {
             template.sendBodyAndHeader("direct:start", "Hello World 1", "isfailed", true);
-            fail("Should throw exception");
-        } catch (Exception e) {
-            // expected
-        }
+        });
         template.sendBodyAndHeader("direct:start", "Hello World 2", "isfailed", false);
 
         mock.assertIsSatisfied();


(camel) 26/36: CAMEL-21196: modernize exception-based assertions in camel-jt400

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit d08757e3220c9137933d2f77f470e7504e869777
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:44:51 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jt400
    
    Replace try-catch-fail patterns with assertThrows in test classes to use
    modern JUnit 5 exception testing approach, improving code clarity and consistency.
---
 .../jt400/Jt400ComponentDefaultConnectionPoolTest.java     | 14 +++++---------
 .../Jt400ComponentDefaultSecureConnectionPoolTest.java     | 14 +++++---------
 .../apache/camel/component/jt400/Jt400ComponentTest.java   | 10 +++-------
 3 files changed, 13 insertions(+), 25 deletions(-)

diff --git a/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultConnectionPoolTest.java b/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultConnectionPoolTest.java
index f87b76aeb1df..7cfd47d331b0 100644
--- a/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultConnectionPoolTest.java
+++ b/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultConnectionPoolTest.java
@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class Jt400ComponentDefaultConnectionPoolTest extends Jt400TestSupport {
     private Jt400Component component;
@@ -30,14 +30,10 @@ public class Jt400ComponentDefaultConnectionPoolTest extends Jt400TestSupport {
     public void doPostSetup() {
         component = new Jt400Component();
         component.setCamelContext(context);
-        try {
-            // Use an invalid object type so that endpoints are never created
-            // and actual connections are never requested
-            component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.xxx");
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            /* Expected */
-        }
+        // Use an invalid object type so that endpoints are never created
+        // and actual connections are never requested
+        assertThrows(Exception.class,
+                () -> component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.xxx"));
     }
 
     @Override
diff --git a/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultSecureConnectionPoolTest.java b/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultSecureConnectionPoolTest.java
index 6390df1d601a..6816f2ab10a9 100644
--- a/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultSecureConnectionPoolTest.java
+++ b/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentDefaultSecureConnectionPoolTest.java
@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class Jt400ComponentDefaultSecureConnectionPoolTest extends Jt400TestSupport {
     private Jt400Component component;
@@ -30,14 +30,10 @@ public class Jt400ComponentDefaultSecureConnectionPoolTest extends Jt400TestSupp
     public void doPostSetup() {
         component = new Jt400Component();
         component.setCamelContext(context);
-        try {
-            // Use an invalid object type so that endpoints are never created
-            // and actual connections are never requested
-            component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.xxx?secured=true");
-            fail("Should have thrown exception");
-        } catch (Exception e) {
-            /* Expected */
-        }
+        // Use an invalid object type so that endpoints are never created
+        // and actual connections are never requested
+        assertThrows(Exception.class,
+                () -> component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.xxx?secured=true"));
     }
 
     @Override
diff --git a/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentTest.java b/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentTest.java
index a05128fd4ee3..c67d437bf7a7 100644
--- a/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentTest.java
+++ b/components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400ComponentTest.java
@@ -20,8 +20,8 @@ import org.apache.camel.Endpoint;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * Test case for {@link Jt400Component}
@@ -63,12 +63,8 @@ public class Jt400ComponentTest extends Jt400TestSupport {
      */
     @Test
     public void testCreateEndpointForOtherObjectType() {
-        try {
-            component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.xxx");
-            fail("Exception should been thrown when trying to create an endpoint for an unsupported object type");
-        } catch (Exception e) {
-            // this is just what we expected
-        }
+        assertThrows(Exception.class,
+                () -> component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.xxx"));
     }
 
     /**


(camel) 15/36: CAMEL-21196: Modernize exception-based assertions in camel-aws

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 5b979e64308886fd7c31bf1184813d42962622a8
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:11:48 2026 +0000

    CAMEL-21196: Modernize exception-based assertions in camel-aws
    
    Replace try-catch-fail pattern with assertDoesNotThrow and assertThrows
    for more idiomatic JUnit 5 exception testing in KinesisConsumerClosedShardWithFailTest.
    Also removed unused fail() import.
---
 .../aws2/kinesis/KinesisConsumerClosedShardWithFailTest.java      | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)

diff --git a/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerClosedShardWithFailTest.java b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerClosedShardWithFailTest.java
index 00db8d79953f..6c19438dc4bf 100644
--- a/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerClosedShardWithFailTest.java
+++ b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerClosedShardWithFailTest.java
@@ -42,8 +42,8 @@ import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;
 import static org.awaitility.Awaitility.await;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.verify;
@@ -98,11 +98,7 @@ public class KinesisConsumerClosedShardWithFailTest {
 
     @Test
     public void itObtainsAShardIteratorOnFirstPoll() {
-        try {
-            underTest.poll();
-        } catch (Exception e) {
-            fail("The first call should not throw an exception");
-        }
+        assertDoesNotThrow(underTest::poll);
         assertThrows(IllegalStateException.class, () -> {
             underTest.poll();
         });


(camel) 30/36: CAMEL-21196: modernize exception-based assertions in camel-sjms2

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 7d7c9f1d6fff347f5a6890aa96cf354deb0b46bb
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:46:48 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-sjms2
    
    Replace try-catch-fail patterns with simple throws in Sjms2EndpointTest.java:
    - testDefaultExchangePattern
    - testInOnlyExchangePattern
    - testInOutExchangePattern
---
 .../camel/component/sjms2/Sjms2EndpointTest.java   | 37 +++++++---------------
 1 file changed, 12 insertions(+), 25 deletions(-)

diff --git a/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/Sjms2EndpointTest.java b/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/Sjms2EndpointTest.java
index 86512e141f82..92e81cf566d4 100644
--- a/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/Sjms2EndpointTest.java
+++ b/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/Sjms2EndpointTest.java
@@ -30,7 +30,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
 
 public class Sjms2EndpointTest extends CamelTestSupport {
 
@@ -98,36 +97,24 @@ public class Sjms2EndpointTest extends CamelTestSupport {
     }
 
     @Test
-    public void testDefaultExchangePattern() {
-        try {
-            Sjms2Endpoint sjms = (Sjms2Endpoint) context.getEndpoint("sjms2:queue:test");
-            assertNotNull(sjms);
-            assertEquals(ExchangePattern.InOnly, sjms.getExchangePattern());
-        } catch (Exception e) {
-            fail("Exception thrown: " + e.getLocalizedMessage());
-        }
+    public void testDefaultExchangePattern() throws Exception {
+        Sjms2Endpoint sjms = (Sjms2Endpoint) context.getEndpoint("sjms2:queue:test");
+        assertNotNull(sjms);
+        assertEquals(ExchangePattern.InOnly, sjms.getExchangePattern());
     }
 
     @Test
-    public void testInOnlyExchangePattern() {
-        try {
-            Endpoint sjms = context.getEndpoint("sjms2:queue:test?exchangePattern=" + ExchangePattern.InOnly);
-            assertNotNull(sjms);
-            assertEquals(ExchangePattern.InOnly, sjms.createExchange().getPattern());
-        } catch (Exception e) {
-            fail("Exception thrown: " + e.getLocalizedMessage());
-        }
+    public void testInOnlyExchangePattern() throws Exception {
+        Endpoint sjms = context.getEndpoint("sjms2:queue:test?exchangePattern=" + ExchangePattern.InOnly);
+        assertNotNull(sjms);
+        assertEquals(ExchangePattern.InOnly, sjms.createExchange().getPattern());
     }
 
     @Test
-    public void testInOutExchangePattern() {
-        try {
-            Endpoint sjms = context.getEndpoint("sjms2:queue:test?exchangePattern=" + ExchangePattern.InOut);
-            assertNotNull(sjms);
-            assertEquals(ExchangePattern.InOut, sjms.createExchange().getPattern());
-        } catch (Exception e) {
-            fail("Exception thrown: " + e.getLocalizedMessage());
-        }
+    public void testInOutExchangePattern() throws Exception {
+        Endpoint sjms = context.getEndpoint("sjms2:queue:test?exchangePattern=" + ExchangePattern.InOut);
+        assertNotNull(sjms);
+        assertEquals(ExchangePattern.InOut, sjms.createExchange().getPattern());
     }
 
     @Test


(camel) 29/36: CAMEL-21196: modernize exception-based assertions in camel-jira

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 6f55a3eebad4f8bb03e12df847c257c53900fff5
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:46:26 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-jira
    
    Replace try-catch-fail patterns with assertThrows in test classes to use
    modern JUnit 5 exception testing approach, improving code clarity and consistency.
---
 .../jira/producer/AddIssueLinkProducerTest.java    | 35 ++++++++--------------
 .../jira/producer/AddWorkLogProducerTest.java      | 35 ++++++++--------------
 .../jira/producer/FetchCommentsProducerTest.java   | 13 ++++----
 .../jira/producer/FetchIssueProducerTest.java      | 13 ++++----
 4 files changed, 36 insertions(+), 60 deletions(-)

diff --git a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddIssueLinkProducerTest.java b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddIssueLinkProducerTest.java
index 30c63c72b542..6b39b8f0606e 100644
--- a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddIssueLinkProducerTest.java
+++ b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddIssueLinkProducerTest.java
@@ -55,7 +55,7 @@ import static org.apache.camel.component.jira.Utils.createIssueWithLinks;
 import static org.apache.camel.component.jira.Utils.newIssueLink;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.apache.camel.test.junit5.TestSupport.assertStringContains;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.lenient;
 import static org.mockito.Mockito.never;
@@ -175,13 +175,10 @@ public class AddIssueLinkProducerTest extends CamelTestSupport {
         headers.put(CHILD_ISSUE_KEY, childIssue.getKey());
         headers.put(LINK_TYPE, linkType);
 
-        try {
-            template.sendBodyAndHeaders(comment, headers);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), PARENT_ISSUE_KEY);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeaders(comment, headers));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), PARENT_ISSUE_KEY);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
@@ -197,13 +194,10 @@ public class AddIssueLinkProducerTest extends CamelTestSupport {
         headers.put(PARENT_ISSUE_KEY, parentIssue.getKey());
         headers.put(LINK_TYPE, linkType);
 
-        try {
-            template.sendBodyAndHeaders(comment, headers);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), CHILD_ISSUE_KEY);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeaders(comment, headers));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), CHILD_ISSUE_KEY);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
@@ -218,13 +212,10 @@ public class AddIssueLinkProducerTest extends CamelTestSupport {
         headers.put(PARENT_ISSUE_KEY, parentIssue.getKey());
         headers.put(CHILD_ISSUE_KEY, childIssue.getKey());
 
-        try {
-            template.sendBodyAndHeaders(comment, headers);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), LINK_TYPE);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeaders(comment, headers));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), LINK_TYPE);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
diff --git a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddWorkLogProducerTest.java b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddWorkLogProducerTest.java
index 1e069bfdffa9..b227add2a373 100644
--- a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddWorkLogProducerTest.java
+++ b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/AddWorkLogProducerTest.java
@@ -56,7 +56,7 @@ import static org.apache.camel.component.jira.Utils.createIssueWithWorkLogs;
 import static org.apache.camel.component.jira.Utils.newWorkLog;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.apache.camel.test.junit5.TestSupport.assertStringContains;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.lenient;
@@ -150,13 +150,10 @@ public class AddWorkLogProducerTest extends CamelTestSupport {
         headers.put(MINUTES_SPENT, minutesSpent);
         String comment = "A new test comment " + new Date();
 
-        try {
-            template.sendBodyAndHeaders(comment, headers);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), ISSUE_KEY);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeaders(comment, headers));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), ISSUE_KEY);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
@@ -171,13 +168,10 @@ public class AddWorkLogProducerTest extends CamelTestSupport {
         headers.put(ISSUE_KEY, backendIssue.getKey());
         String comment = "A new test comment " + new Date();
 
-        try {
-            template.sendBodyAndHeaders(comment, headers);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), MINUTES_SPENT);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeaders(comment, headers));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), MINUTES_SPENT);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
@@ -193,13 +187,10 @@ public class AddWorkLogProducerTest extends CamelTestSupport {
         headers.put(ISSUE_KEY, backendIssue.getKey());
         headers.put(MINUTES_SPENT, minutesSpent);
 
-        try {
-            template.sendBodyAndHeaders(null, headers);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), "Missing exchange body");
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeaders(null, headers));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), "Missing exchange body");
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
diff --git a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchCommentsProducerTest.java b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchCommentsProducerTest.java
index 4345092ee316..6d35dee8e8c6 100644
--- a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchCommentsProducerTest.java
+++ b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchCommentsProducerTest.java
@@ -42,7 +42,7 @@ import static org.apache.camel.component.jira.JiraConstants.JIRA_REST_CLIENT_FAC
 import static org.apache.camel.component.jira.JiraTestConstants.JIRA_CREDENTIALS;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.apache.camel.test.junit5.TestSupport.assertStringContains;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.lenient;
 import static org.mockito.Mockito.never;
@@ -117,13 +117,10 @@ public class FetchCommentsProducerTest extends CamelTestSupport {
 
     @Test
     public void testFetchCommentsMissingIssueKey() throws InterruptedException {
-        try {
-            template.sendBody(null);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), ISSUE_KEY);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody(null));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), ISSUE_KEY);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();
diff --git a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchIssueProducerTest.java b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchIssueProducerTest.java
index 109519d09f02..836c2d7b3915 100644
--- a/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchIssueProducerTest.java
+++ b/components/camel-jira/src/test/java/org/apache/camel/component/jira/producer/FetchIssueProducerTest.java
@@ -42,7 +42,7 @@ import static org.apache.camel.component.jira.JiraConstants.JIRA_REST_CLIENT_FAC
 import static org.apache.camel.component.jira.JiraTestConstants.JIRA_CREDENTIALS;
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
 import static org.apache.camel.test.junit5.TestSupport.assertStringContains;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.lenient;
 import static org.mockito.Mockito.never;
@@ -116,13 +116,10 @@ public class FetchIssueProducerTest extends CamelTestSupport {
 
     @Test
     public void testFetchIssueMissingIssueKey() throws InterruptedException {
-        try {
-            template.sendBody(null);
-            fail("Should have thrown an exception");
-        } catch (CamelExecutionException e) {
-            IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
-            assertStringContains(cause.getMessage(), ISSUE_KEY);
-        }
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBody(null));
+        IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertStringContains(cause.getMessage(), ISSUE_KEY);
 
         mockResult.expectedMessageCount(0);
         mockResult.assertIsSatisfied();


(camel) 09/36: CAMEL-21196: modernize exception-based assertions in camel-test

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit df4bf3cdc87bbadba8fea47386c292cd7b7900ee
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 18:39:12 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-test
---
 .../camel/test/junit5/patterns/AdviceWithNotStartedTest.java   | 10 ++++------
 .../apache/camel/test/junit5/patterns/AsyncSendMockTest.java   |  9 +++------
 .../camel/test/junit6/patterns/AdviceWithNotStartedTest.java   | 10 ++++------
 .../apache/camel/test/junit6/patterns/AsyncSendMockTest.java   |  9 +++------
 4 files changed, 14 insertions(+), 24 deletions(-)

diff --git a/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AdviceWithNotStartedTest.java b/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AdviceWithNotStartedTest.java
index d8d7b470d1f1..7b7825eaa011 100644
--- a/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AdviceWithNotStartedTest.java
+++ b/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AdviceWithNotStartedTest.java
@@ -28,7 +28,7 @@ import org.apache.camel.test.junit5.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class AdviceWithNotStartedTest extends CamelTestSupport {
 
@@ -48,12 +48,10 @@ public class AdviceWithNotStartedTest extends CamelTestSupport {
 
         getMockEndpoint("mock:result").expectedMessageCount(1);
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.sendBody("direct:start", "Hello World");
-            fail("Should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(RejectedExecutionException.class, e.getCause());
-        }
+        });
+        assertIsInstanceOf(RejectedExecutionException.class, e.getCause());
 
         // start Camel
         context.start();
diff --git a/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AsyncSendMockTest.java b/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AsyncSendMockTest.java
index 67e352f16fee..475614ac5d2f 100644
--- a/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AsyncSendMockTest.java
+++ b/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/patterns/AsyncSendMockTest.java
@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 
 public class AsyncSendMockTest extends CamelTestSupport {
     private static final Logger LOG = LoggerFactory.getLogger(AsyncSendMockTest.class);
@@ -35,7 +35,7 @@ public class AsyncSendMockTest extends CamelTestSupport {
 
     @Test
     public void testMakeAsyncApiCall() {
-        try {
+        assertDoesNotThrow(() -> {
             getMockEndpoint("mock:seda:start").expectedHeaderReceived("username", "admin123");
             getMockEndpoint("mock:seda:start").expectedBodiesReceived("Hello");
             DefaultExchange dfex = new DefaultExchange(context);
@@ -44,9 +44,6 @@ public class AsyncSendMockTest extends CamelTestSupport {
             dfex.getIn().setBody("Hello");
             template.asyncSend("seda:start", dfex);
             MockEndpoint.assertIsSatisfied(context);
-        } catch (Exception e) {
-            LOG.warn("Failed to make async call to api: {}", e.getMessage(), e);
-            fail("Failed to make async call to api");
-        }
+        });
     }
 }
diff --git a/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AdviceWithNotStartedTest.java b/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AdviceWithNotStartedTest.java
index f75627b13475..1badcf820084 100644
--- a/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AdviceWithNotStartedTest.java
+++ b/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AdviceWithNotStartedTest.java
@@ -28,7 +28,7 @@ import org.apache.camel.test.junit6.CamelTestSupport;
 import org.junit.jupiter.api.Test;
 
 import static org.apache.camel.test.junit6.TestSupport.assertIsInstanceOf;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class AdviceWithNotStartedTest extends CamelTestSupport {
 
@@ -48,12 +48,10 @@ public class AdviceWithNotStartedTest extends CamelTestSupport {
 
         getMockEndpoint("mock:result").expectedMessageCount(1);
 
-        try {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> {
             template.sendBody("direct:start", "Hello World");
-            fail("Should throw exception");
-        } catch (CamelExecutionException e) {
-            assertIsInstanceOf(RejectedExecutionException.class, e.getCause());
-        }
+        });
+        assertIsInstanceOf(RejectedExecutionException.class, e.getCause());
 
         // start Camel
         context.start();
diff --git a/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AsyncSendMockTest.java b/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AsyncSendMockTest.java
index 9ab3503834a6..dc3e15b930a3 100644
--- a/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AsyncSendMockTest.java
+++ b/components/camel-test/camel-test-junit6/src/test/java/org/apache/camel/test/junit6/patterns/AsyncSendMockTest.java
@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 
 public class AsyncSendMockTest extends CamelTestSupport {
     private static final Logger LOG = LoggerFactory.getLogger(AsyncSendMockTest.class);
@@ -35,7 +35,7 @@ public class AsyncSendMockTest extends CamelTestSupport {
 
     @Test
     public void testMakeAsyncApiCall() {
-        try {
+        assertDoesNotThrow(() -> {
             getMockEndpoint("mock:seda:start").expectedHeaderReceived("username", "admin123");
             getMockEndpoint("mock:seda:start").expectedBodiesReceived("Hello");
             DefaultExchange dfex = new DefaultExchange(context);
@@ -44,9 +44,6 @@ public class AsyncSendMockTest extends CamelTestSupport {
             dfex.getIn().setBody("Hello");
             template.asyncSend("seda:start", dfex);
             MockEndpoint.assertIsSatisfied(context);
-        } catch (Exception e) {
-            LOG.warn("Failed to make async call to api: {}", e.getMessage(), e);
-            fail("Failed to make async call to api");
-        }
+        });
     }
 }


(camel) 35/36: CAMEL-21196: modernize exception-based assertions in camel-platform-http-vertx

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 049b6270019f6b320821368c776f021843afcc24
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:56:02 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-platform-http-vertx
    
    Replace try-catch-fail patterns with JUnit 5 assertThrows for modernized exception testing.
---
 ...PlatformHttpRestOpenApiConsumerRestDslTest.java | 31 +++++++++-----------
 .../vertx/PlatformHttpRestOpenApiConsumerTest.java | 33 ++++++++++------------
 2 files changed, 29 insertions(+), 35 deletions(-)

diff --git a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java
index a242fca8ed36..e320de9ed0f2 100644
--- a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java
+++ b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java
@@ -21,13 +21,13 @@ import java.io.FileInputStream;
 import org.apache.camel.CamelContext;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.util.IOHelper;
-import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
 import static io.restassured.RestAssured.given;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.equalToCompressingWhiteSpace;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class PlatformHttpRestOpenApiConsumerRestDslTest {
 
@@ -134,22 +134,19 @@ public class PlatformHttpRestOpenApiConsumerRestDslTest {
         final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
 
         try {
-            context.addRoutes(new RouteBuilder() {
-                @Override
-                public void configure() {
-                    rest().openApi("openapi-v3.json");
-
-                    from("direct:getPetById")
-                            .setBody().constant("{\"pet\": \"tony the tiger\"}");
-                }
-            });
-
-            context.start();
-            fail();
-        } catch (Exception e) {
-            Assertions.assertTrue(
-                    e.getCause().getMessage()
-                            .startsWith("OpenAPI specification has 18 unmapped operations to corresponding routes"));
+            assertThrows(Exception.class, () -> {
+                context.addRoutes(new RouteBuilder() {
+                    @Override
+                    public void configure() {
+                        rest().openApi("openapi-v3.json");
+
+                        from("direct:getPetById")
+                                .setBody().constant("{\"pet\": \"tony the tiger\"}");
+                    }
+                });
+
+                context.start();
+            }, "OpenAPI specification has 18 unmapped operations to corresponding routes");
         } finally {
             context.stop();
         }
diff --git a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java
index 8bf85c8d23a1..e494ff86b058 100644
--- a/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java
+++ b/components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerTest.java
@@ -19,12 +19,12 @@ package org.apache.camel.component.platform.http.vertx;
 import org.apache.camel.CamelContext;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.component.mock.MockEndpoint;
-import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
 import static io.restassured.RestAssured.given;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.equalToCompressingWhiteSpace;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class PlatformHttpRestOpenApiConsumerTest {
 
@@ -136,23 +136,20 @@ public class PlatformHttpRestOpenApiConsumerTest {
         final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
 
         try {
-            context.addRoutes(new RouteBuilder() {
-                @Override
-                public void configure() {
-                    from("rest-openapi:classpath:openapi-v3.json?missingOperation=fail")
-                            .log("dummy");
-
-                    from("direct:getPetById")
-                            .setBody().constant("{\"pet\": \"tony the tiger\"}");
-                }
-            });
-
-            context.start();
-            fail();
-        } catch (Exception e) {
-            Assertions.assertTrue(
-                    e.getCause().getMessage()
-                            .startsWith("OpenAPI specification has 18 unmapped operations to corresponding routes"));
+            assertThrows(Exception.class, () -> {
+                context.addRoutes(new RouteBuilder() {
+                    @Override
+                    public void configure() {
+                        from("rest-openapi:classpath:openapi-v3.json?missingOperation=fail")
+                                .log("dummy");
+
+                        from("direct:getPetById")
+                                .setBody().constant("{\"pet\": \"tony the tiger\"}");
+                    }
+                });
+
+                context.start();
+            }, "OpenAPI specification has 18 unmapped operations to corresponding routes");
         } finally {
             context.stop();
         }


(camel) 25/36: CAMEL-21196: modernize exception-based assertions in camel-servlet

Posted by or...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit a1c4bd60a26db69d42f7ee8ce00547894400f5ae
Author: Otavio Rodolfo Piske <an...@gmail.com>
AuthorDate: Sat Jan 24 19:44:50 2026 +0000

    CAMEL-21196: modernize exception-based assertions in camel-servlet
    
    Replace try-catch-fail patterns with assertThrows in:
    - HttpClientRouteTest.java (2 occurrences)
    - MultiServletConsumerTest.java (2 occurrences)
    - ServletChoiceBeanTest.java (1 occurrence)
---
 .../component/servlet/MultiServletConsumerTest.java  | 20 +++++++-------------
 .../component/servlet/ServletChoiceBeanTest.java     | 10 +++-------
 2 files changed, 10 insertions(+), 20 deletions(-)

diff --git a/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/MultiServletConsumerTest.java b/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/MultiServletConsumerTest.java
index ce8f81dd6896..9bb1c6eb82ca 100644
--- a/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/MultiServletConsumerTest.java
+++ b/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/MultiServletConsumerTest.java
@@ -22,7 +22,7 @@ import org.apache.camel.builder.RouteBuilder;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class MultiServletConsumerTest extends ServletCamelRouterTestSupport {
 
@@ -37,19 +37,13 @@ public class MultiServletConsumerTest extends ServletCamelRouterTestSupport {
 
     @Test
     public void testMultiServletsConsumersCannotAccessEachOther() throws Exception {
-        try {
-            getService("/services2/hello?name=Camel");
-            fail("Should have thrown an exception");
-        } catch (HttpNotFoundException e) {
-            assertEquals(404, e.getResponseCode());
-        }
+        HttpNotFoundException e = assertThrows(HttpNotFoundException.class,
+                () -> getService("/services2/hello?name=Camel"));
+        assertEquals(404, e.getResponseCode());
 
-        try {
-            getService("/services1/echo?name=Camel");
-            fail("Should have thrown an exception");
-        } catch (HttpNotFoundException e) {
-            assertEquals(404, e.getResponseCode());
-        }
+        e = assertThrows(HttpNotFoundException.class,
+                () -> getService("/services1/echo?name=Camel"));
+        assertEquals(404, e.getResponseCode());
     }
 
     public String getService(String path) throws Exception {
diff --git a/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/ServletChoiceBeanTest.java b/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/ServletChoiceBeanTest.java
index fd2b01fe8c97..9e12e60c0c05 100644
--- a/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/ServletChoiceBeanTest.java
+++ b/components/camel-servlet/src/test/java/org/apache/camel/component/servlet/ServletChoiceBeanTest.java
@@ -22,7 +22,7 @@ import org.apache.camel.component.mock.MockEndpoint;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class ServletChoiceBeanTest extends ServletCamelRouterTestSupport {
 
@@ -45,12 +45,8 @@ public class ServletChoiceBeanTest extends ServletCamelRouterTestSupport {
         getMockEndpoint("mock:bean").expectedMessageCount(1);
 
         WebRequest req = new GetMethodWebRequest(contextUrl + "/services/hello");
-        try {
-            query(req);
-            fail("Should throw exception");
-        } catch (HttpNotFoundException e) {
-            assertEquals(404, e.getResponseCode());
-        }
+        HttpNotFoundException e = assertThrows(HttpNotFoundException.class, () -> query(req));
+        assertEquals(404, e.getResponseCode());
 
         MockEndpoint.assertIsSatisfied(context);
     }