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 25f0b15b13032aaadc2a31c7f3b3a3de98e950f8 Author: Otavio Rodolfo Piske <angusyo...@gmail.com> AuthorDate: Fri May 10 14:46:05 2024 +0200 (chores) camel-test: code cleanup - use is empty - minor cleanups - avoid NPE - break larger code in smaller pieces - simplify assertions - use modern lambda expressions - reuse builtin code - use lambdas when cleaner to do so - use text block when possible - use final when possible --- .../org/apache/camel/test/AvailablePortFinder.java | 2 +- .../camel/test/CamelRouteCoverageDumper.java | 3 +- .../test/ExcludingPackageScanClassResolver.java | 2 +- .../apache/camel/test/junit5/CamelTestSupport.java | 235 ++++++++++++--------- .../org/apache/camel/test/junit5/TestSupport.java | 19 +- .../camel/test/junit5/ThrottlingExecutor.java | 4 +- .../camel/test/junit5/CamelTestSupportTest.java | 8 +- .../spring/junit5/CamelAnnotationsHandler.java | 74 +++---- .../junit5/CamelSpringBootExecutionListener.java | 2 +- .../test/spring/junit5/CamelSpringTestHelper.java | 6 +- .../test/spring/junit5/CamelSpringTestSupport.java | 2 +- .../junit5/StopWatchTestExecutionListener.java | 2 +- .../AdviceWithOnExceptionMultipleIssueTest.java | 21 +- .../AdviceWithOnExceptionTransactedTest.java | 5 +- .../spring/CamelSpringProvidesBreakpointTest.java | 3 +- .../test/spring/CamelSpringTestSupportTest.java | 8 +- .../SpringTestExecutionListenerSorterTest.java | 4 +- 17 files changed, 210 insertions(+), 190 deletions(-) diff --git a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/AvailablePortFinder.java b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/AvailablePortFinder.java index 55b651b985c..31644d01986 100644 --- a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/AvailablePortFinder.java +++ b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/AvailablePortFinder.java @@ -43,7 +43,7 @@ public final class AvailablePortFinder { public class Port implements BeforeEachCallback, AfterAllCallback, AutoCloseable { final int port; String testClass; - Throwable creation; + final Throwable creation; public Port(int port) { this.port = port; diff --git a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/CamelRouteCoverageDumper.java b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/CamelRouteCoverageDumper.java index 43410d76423..fc2c72c2597 100644 --- a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/CamelRouteCoverageDumper.java +++ b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/CamelRouteCoverageDumper.java @@ -22,7 +22,6 @@ import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -113,7 +112,7 @@ public class CamelRouteCoverageDumper { // sort processors by position in route definition for (Map.Entry<String, List<ManagedProcessorMBean>> entry : processorsForRoute.entrySet()) { - Collections.sort(entry.getValue(), Comparator.comparing(ManagedProcessorMBean::getIndex)); + entry.getValue().sort(Comparator.comparing(ManagedProcessorMBean::getIndex)); } return processorsForRoute; diff --git a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/ExcludingPackageScanClassResolver.java b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/ExcludingPackageScanClassResolver.java index ce04f9ea766..4bcfd9f5a93 100644 --- a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/ExcludingPackageScanClassResolver.java +++ b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/ExcludingPackageScanClassResolver.java @@ -26,7 +26,7 @@ import org.apache.camel.impl.scan.InvertingPackageScanFilter; public class ExcludingPackageScanClassResolver extends DefaultPackageScanClassResolver { public void setExcludedClasses(Set<Class<?>> excludedClasses) { - Set<Class<?>> parents = excludedClasses == null ? Collections.<Class<?>> emptySet() : excludedClasses; + Set<Class<?>> parents = excludedClasses == null ? Collections.emptySet() : excludedClasses; addFilter(new InvertingPackageScanFilter(new AssignableToPackageScanFilter(parents))); } diff --git a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/CamelTestSupport.java b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/CamelTestSupport.java index a7f486d0ccd..4aae8bc3962 100644 --- a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/CamelTestSupport.java +++ b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/CamelTestSupport.java @@ -351,26 +351,7 @@ public abstract class CamelTestSupport doQuarkusCheck(); if (isCreateCamelContextPerClass()) { - INSTANCE.set(this); - AtomicInteger v = TESTS.get(); - if (v == null) { - v = new AtomicInteger(); - TESTS.set(v); - } - if (v.getAndIncrement() == 0) { - LOG.debug("Setup CamelContext before running first test"); - // test is per class, so only setup once (the first time) - doSpringBootCheck(); - setupResources(); - doPreSetup(); - doSetUp(); - doPostSetup(); - } else { - LOG.debug("Reset between test methods"); - // and in between tests we must do IoC and reset mocks - postProcessTest(); - MockEndpoint.resetMocks(context); - } + createCamelContextPerClass(); } else { // test is per test so always setup setupResources(); @@ -383,6 +364,29 @@ public abstract class CamelTestSupport watch.restart(); } + private void createCamelContextPerClass() throws Exception { + INSTANCE.set(this); + AtomicInteger v = TESTS.get(); + if (v == null) { + v = new AtomicInteger(); + TESTS.set(v); + } + if (v.getAndIncrement() == 0) { + LOG.debug("Setup CamelContext before running first test"); + // test is per class, so only setup once (the first time) + doSpringBootCheck(); + setupResources(); + doPreSetup(); + doSetUp(); + doPostSetup(); + } else { + LOG.debug("Reset between test methods"); + // and in between tests we must do IoC and reset mocks + postProcessTest(); + MockEndpoint.resetMocks(context); + } + } + /** * Strategy to perform any pre setup, before {@link CamelContext} is created */ @@ -445,17 +449,36 @@ public abstract class CamelTestSupport // set debugger if enabled if (isUseDebugger()) { - if (context.getStatus().equals(ServiceStatus.Started)) { - LOG.info("Cannot setting the Debugger to the starting CamelContext, stop the CamelContext now."); - // we need to stop the context first to setup the debugger - context.stop(); - } - context.setDebugging(true); - context.setDebugger(new DefaultDebugger()); - context.getDebugger().addBreakpoint(breakpoint); - // when stopping CamelContext it will automatically remove the breakpoint + setupDebugger(); + } + + setupTemplates(); + + // enable auto mocking if enabled + enableAutoMocking(); + + // configure properties component (mandatory for testing) + configurePropertiesComponent(); + + setupIncludeExcludePatterns(); + + // prepare for in-between tests + postProcessTest(); + + if (isUseRouteBuilder()) { + setupRoutes(); + + tryStartCamelContext(); + } else { + replaceFromEndpoints(); + LOG.debug("Using route builder from the created context: {}", context); } + LOG.debug("Routing Rules are: {}", context.getRoutes()); + assertValidContext(context); + } + + private void setupTemplates() { template = context.createProducerTemplate(); template.start(); fluentTemplate = context.createFluentProducerTemplate(); @@ -466,20 +489,49 @@ public abstract class CamelTestSupport THREAD_TEMPLATE.set(template); THREAD_FLUENT_TEMPLATE.set(fluentTemplate); THREAD_CONSUMER.set(consumer); + } - // enable auto mocking if enabled - String pattern = isMockEndpoints(); - if (pattern != null) { - context.getCamelContextExtension() - .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern)); + private void setupRoutes() throws Exception { + RoutesBuilder[] builders = createRouteBuilders(); + // add configuration before routes + for (RoutesBuilder builder : builders) { + if (builder instanceof RouteConfigurationsBuilder) { + LOG.debug("Using created route configuration: {}", builder); + context.addRoutesConfigurations((RouteConfigurationsBuilder) builder); + } } - pattern = isMockEndpointsAndSkip(); - if (pattern != null) { - context.getCamelContextExtension() - .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern, true)); + for (RoutesBuilder builder : builders) { + LOG.debug("Using created route builder to add routes: {}", builder); + context.addRoutes(builder); + } + for (RoutesBuilder builder : builders) { + LOG.debug("Using created route builder to add templated routes: {}", builder); + context.addTemplatedRoutes(builder); } + replaceFromEndpoints(); + } - // configure properties component (mandatory for testing) + private void tryStartCamelContext() throws Exception { + boolean skip = Boolean.parseBoolean(System.getProperty("skipStartingCamelContext")); + if (skip) { + LOG.info("Skipping starting CamelContext as system property skipStartingCamelContext is set to be true."); + } else if (isUseAdviceWith()) { + LOG.info("Skipping starting CamelContext as isUseAdviceWith is set to true."); + } else { + startCamelContext(); + } + } + + private void setupIncludeExcludePatterns() { + final String include = getRouteFilterIncludePattern(); + final String exclude = getRouteFilterExcludePattern(); + if (include != null || exclude != null) { + LOG.info("Route filtering pattern: include={}, exclude={}", include, exclude); + context.getCamelContextExtension().getContextPlugin(Model.class).setRouteFilterPattern(include, exclude); + } + } + + private void configurePropertiesComponent() { PropertiesComponent pc = context.getPropertiesComponent(); if (extra == null) { extra = useOverridePropertiesWithPropertiesComponent(); @@ -502,50 +554,31 @@ public abstract class CamelTestSupport if (ignore != null) { pc.setIgnoreMissingLocation(ignore); } + } - String include = getRouteFilterIncludePattern(); - String exclude = getRouteFilterExcludePattern(); - if (include != null || exclude != null) { - LOG.info("Route filtering pattern: include={}, exclude={}", include, exclude); - context.getCamelContextExtension().getContextPlugin(Model.class).setRouteFilterPattern(include, exclude); + private void enableAutoMocking() { + String pattern = isMockEndpoints(); + if (pattern != null) { + context.getCamelContextExtension() + .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern)); } - - // prepare for in-between tests - postProcessTest(); - - if (isUseRouteBuilder()) { - RoutesBuilder[] builders = createRouteBuilders(); - // add configuration before routes - for (RoutesBuilder builder : builders) { - if (builder instanceof RouteConfigurationsBuilder) { - LOG.debug("Using created route configuration: {}", builder); - context.addRoutesConfigurations((RouteConfigurationsBuilder) builder); - } - } - for (RoutesBuilder builder : builders) { - LOG.debug("Using created route builder to add routes: {}", builder); - context.addRoutes(builder); - } - for (RoutesBuilder builder : builders) { - LOG.debug("Using created route builder to add templated routes: {}", builder); - context.addTemplatedRoutes(builder); - } - replaceFromEndpoints(); - boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext")); - if (skip) { - LOG.info("Skipping starting CamelContext as system property skipStartingCamelContext is set to be true."); - } else if (isUseAdviceWith()) { - LOG.info("Skipping starting CamelContext as isUseAdviceWith is set to true."); - } else { - startCamelContext(); - } - } else { - replaceFromEndpoints(); - LOG.debug("Using route builder from the created context: {}", context); + pattern = isMockEndpointsAndSkip(); + if (pattern != null) { + context.getCamelContextExtension() + .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern, true)); } - LOG.debug("Routing Rules are: {}", context.getRoutes()); + } - assertValidContext(context); + private void setupDebugger() { + if (context.getStatus().equals(ServiceStatus.Started)) { + LOG.info("Cannot setting the Debugger to the starting CamelContext, stop the CamelContext now."); + // we need to stop the context first to setup the debugger + context.stop(); + } + context.setDebugging(true); + context.setDebugger(new DefaultDebugger()); + context.getDebugger().addBreakpoint(breakpoint); + // when stopping CamelContext it will automatically remove the breakpoint } private void replaceFromEndpoints() throws Exception { @@ -573,31 +606,37 @@ public abstract class CamelTestSupport // if we should dump route stats, then write that to a file if (isRouteCoverageEnabled()) { - String className = this.getClass().getSimpleName(); - String dir = "target/camel-route-coverage"; - String name = className + "-" + StringHelper.before(currentTestName, "(") + ".xml"; - - ManagedCamelContext mc - = context != null ? context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class) : null; - ManagedCamelContextMBean managedCamelContext = mc != null ? mc.getManagedCamelContext() : null; - if (managedCamelContext == null) { - LOG.warn("Cannot dump route coverage to file as JMX is not enabled. " - + "Add camel-management JAR as dependency and/or override useJmx() method to enable JMX in the unit test classes."); - } else { - routeCoverageDumper.dump(managedCamelContext, context, dir, name, getClass().getName(), currentTestName, - timeTaken()); - } + dumpRouteCoverage(); } LOG.info(SEPARATOR); if (isCreateCamelContextPerClass()) { // will tear down test specially in afterAll callback + return; + } + + LOG.debug("tearDown()"); + doStopTemplates(consumer, template, fluentTemplate); + doStopCamelContext(context, camelContextService); + doPostTearDown(); + cleanupResources(); + + } + + private void dumpRouteCoverage() throws Exception { + String className = this.getClass().getSimpleName(); + String dir = "target/camel-route-coverage"; + String name = className + "-" + StringHelper.before(currentTestName, "(") + ".xml"; + + ManagedCamelContext mc + = context != null ? context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class) : null; + ManagedCamelContextMBean managedCamelContext = mc != null ? mc.getManagedCamelContext() : null; + if (managedCamelContext == null) { + LOG.warn("Cannot dump route coverage to file as JMX is not enabled. " + + "Add camel-management JAR as dependency and/or override useJmx() method to enable JMX in the unit test classes."); } else { - LOG.debug("tearDown()"); - doStopTemplates(consumer, template, fluentTemplate); - doStopCamelContext(context, camelContextService); - doPostTearDown(); - cleanupResources(); + routeCoverageDumper.dump(managedCamelContext, context, dir, name, getClass().getName(), currentTestName, + timeTaken()); } } diff --git a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/TestSupport.java b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/TestSupport.java index dbdb99fc5a7..e80e511e34d 100644 --- a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/TestSupport.java +++ b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/TestSupport.java @@ -191,16 +191,21 @@ public final class TestSupport { * Asserts that the given expression when evaluated returns the given answer. */ public static Object assertExpression(Expression expression, Exchange exchange, Object expectedAnswer) { + final Object actualAnswer = getActualAnswer(expression, exchange, expectedAnswer); + + LOG.debug("Evaluated expression: {} on exchange: {} result: {}", expression, exchange, actualAnswer); + + assertEquals(expectedAnswer, actualAnswer, "Expression: " + expression + " on Exchange: " + exchange); + return actualAnswer; + } + + private static Object getActualAnswer(Expression expression, Exchange exchange, Object expectedAnswer) { Object actualAnswer; if (expectedAnswer != null) { actualAnswer = expression.evaluate(exchange, expectedAnswer.getClass()); } else { actualAnswer = expression.evaluate(exchange, Object.class); } - - LOG.debug("Evaluated expression: {} on exchange: {} result: {}", expression, exchange, actualAnswer); - - assertEquals(expectedAnswer, actualAnswer, "Expression: " + expression + " on Exchange: " + exchange); return actualAnswer; } @@ -483,8 +488,10 @@ public final class TestSupport { if (file.isDirectory()) { File[] files = file.listFiles(); - for (File child : files) { - recursivelyDeleteDirectory(child); + if (files != null) { + for (File child : files) { + recursivelyDeleteDirectory(child); + } } } try { diff --git a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/ThrottlingExecutor.java b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/ThrottlingExecutor.java index fbeab6f3938..1afee21ee81 100644 --- a/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/ThrottlingExecutor.java +++ b/components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/ThrottlingExecutor.java @@ -24,8 +24,8 @@ import java.util.function.IntConsumer; public final class ThrottlingExecutor { - private List<IntConsumer> beforeTasks = new ArrayList<>(); - private List<IntConsumer> afterTasks = new ArrayList<>(); + private final List<IntConsumer> beforeTasks = new ArrayList<>(); + private final List<IntConsumer> afterTasks = new ArrayList<>(); private int repetitions; private long beforeWait; private long awaiting; diff --git a/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/CamelTestSupportTest.java b/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/CamelTestSupportTest.java index 29aaccdb198..2d11070c6d2 100644 --- a/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/CamelTestSupportTest.java +++ b/components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/CamelTestSupportTest.java @@ -45,16 +45,12 @@ public class CamelTestSupportTest extends CamelTestSupport { @Test public void exceptionThrownWhenEndpointNotFoundAndNoCreate() { - assertThrows(NoSuchEndpointException.class, () -> { - getMockEndpoint("mock:bogus", false); - }); + assertThrows(NoSuchEndpointException.class, () -> getMockEndpoint("mock:bogus", false)); } @Test public void exceptionThrownWhenEndpointNotAMockEndpoint() { - assertThrows(NoSuchEndpointException.class, () -> { - getMockEndpoint("direct:something", false); - }); + assertThrows(NoSuchEndpointException.class, () -> getMockEndpoint("direct:something", false)); } @Test diff --git a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java index 70a05178f20..0db5f23738c 100644 --- a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java +++ b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java @@ -209,24 +209,20 @@ public final class CamelAnnotationsHandler { } if (!breakpoints.isEmpty()) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() { - - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { + CamelSpringTestHelper.doToSpringCamelContexts(context, (contextName, camelContext) -> { - // automatic turn on debugging when we have breakpoints - camelContext.setDebugging(true); + // automatic turn on debugging when we have breakpoints + camelContext.setDebugging(true); - Debugger debugger = camelContext.getDebugger(); - if (debugger == null) { - debugger = new DefaultDebugger(); - camelContext.setDebugger(debugger); - } + Debugger debugger = camelContext.getDebugger(); + if (debugger == null) { + debugger = new DefaultDebugger(); + camelContext.setDebugger(debugger); + } - for (Breakpoint breakpoint : breakpoints) { - LOGGER.info("Adding Breakpoint [{}] to CamelContext with name [{}].", breakpoint, contextName); - debugger.addBreakpoint(breakpoint); - } + for (Breakpoint breakpoint : breakpoints) { + LOGGER.info("Adding Breakpoint [{}] to CamelContext with name [{}].", breakpoint, contextName); + debugger.addBreakpoint(breakpoint); } }); } @@ -249,15 +245,11 @@ public final class CamelAnnotationsHandler { shutdownTimeUnit = TimeUnit.SECONDS; } - CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() { - - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - LOGGER.info("Setting shutdown timeout to [{} {}] on CamelContext with name [{}].", shutdownTimeout, - shutdownTimeUnit, contextName); - camelContext.getShutdownStrategy().setTimeout(shutdownTimeout); - camelContext.getShutdownStrategy().setTimeUnit(shutdownTimeUnit); - } + CamelSpringTestHelper.doToSpringCamelContexts(context, (contextName, camelContext) -> { + LOGGER.info("Setting shutdown timeout to [{} {}] on CamelContext with name [{}].", shutdownTimeout, + shutdownTimeUnit, contextName); + camelContext.getShutdownStrategy().setTimeout(shutdownTimeout); + camelContext.getShutdownStrategy().setTimeUnit(shutdownTimeUnit); }); } @@ -270,15 +262,11 @@ public final class CamelAnnotationsHandler { public static void handleMockEndpoints(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { if (testClass.isAnnotationPresent(MockEndpoints.class)) { final String mockEndpoints = testClass.getAnnotation(MockEndpoints.class).value(); - CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() { - - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - LOGGER.info("Enabling auto mocking of endpoints matching pattern [{}] on CamelContext with name [{}].", - mockEndpoints, contextName); - camelContext.getCamelContextExtension() - .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpoints)); - } + CamelSpringTestHelper.doToSpringCamelContexts(context, (contextName, camelContext) -> { + LOGGER.info("Enabling auto mocking of endpoints matching pattern [{}] on CamelContext with name [{}].", + mockEndpoints, contextName); + camelContext.getCamelContextExtension() + .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpoints)); }); } } @@ -293,18 +281,14 @@ public final class CamelAnnotationsHandler { public static void handleMockEndpointsAndSkip(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { if (testClass.isAnnotationPresent(MockEndpointsAndSkip.class)) { final String mockEndpoints = testClass.getAnnotation(MockEndpointsAndSkip.class).value(); - CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() { - - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - // resolve the property place holders of the mockEndpoints - String mockEndpointsValue = camelContext.resolvePropertyPlaceholders(mockEndpoints); - LOGGER.info( - "Enabling auto mocking and skipping of endpoints matching pattern [{}] on CamelContext with name [{}].", - mockEndpointsValue, contextName); - camelContext.getCamelContextExtension() - .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpointsValue, true)); - } + CamelSpringTestHelper.doToSpringCamelContexts(context, (contextName, camelContext) -> { + // resolve the property place holders of the mockEndpoints + String mockEndpointsValue = camelContext.resolvePropertyPlaceholders(mockEndpoints); + LOGGER.info( + "Enabling auto mocking and skipping of endpoints matching pattern [{}] on CamelContext with name [{}].", + mockEndpointsValue, contextName); + camelContext.getCamelContextExtension() + .registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpointsValue, true)); }); } } diff --git a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java index f3a1864270f..ce9af586dc3 100644 --- a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java +++ b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java @@ -25,7 +25,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; public class CamelSpringBootExecutionListener extends AbstractTestExecutionListener { - protected static ThreadLocal<ConfigurableApplicationContext> threadApplicationContext = new ThreadLocal<>(); + protected static final ThreadLocal<ConfigurableApplicationContext> threadApplicationContext = new ThreadLocal<>(); private static final Logger LOG = LoggerFactory.getLogger(CamelSpringBootExecutionListener.class); private static final String PROPERTY_SKIP_STARTING_CAMEL_CONTEXT = "skipStartingCamelContext"; diff --git a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java index 546dfec0d36..b0a8357d17e 100644 --- a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java +++ b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java @@ -37,9 +37,9 @@ import org.springframework.test.context.TestContext; */ public final class CamelSpringTestHelper { - private static ThreadLocal<String> originalJmxDisabledValue = new ThreadLocal<>(); - private static ThreadLocal<String> originalExcludeRoutesValue = new ThreadLocal<>(); - private static ThreadLocal<TestContext> testContext = new ThreadLocal<>(); + private static final ThreadLocal<String> originalJmxDisabledValue = new ThreadLocal<>(); + private static final ThreadLocal<String> originalExcludeRoutesValue = new ThreadLocal<>(); + private static final ThreadLocal<TestContext> testContext = new ThreadLocal<>(); private CamelSpringTestHelper() { } diff --git a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestSupport.java b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestSupport.java index d390c5f6b2c..cc23f556826 100644 --- a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestSupport.java +++ b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestSupport.java @@ -315,7 +315,7 @@ public abstract class CamelSpringTestSupport extends CamelTestSupport { @Override public InputStream getInputStream() throws IOException { - if (properties.size() > 0) { + if (!properties.isEmpty()) { StringWriter sw = new StringWriter(); try (InputStreamReader r = new InputStreamReader(delegate.getInputStream(), StandardCharsets.UTF_8)) { char[] buf = new char[32768]; diff --git a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/StopWatchTestExecutionListener.java b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/StopWatchTestExecutionListener.java index aacc85942c8..7d52c843fb2 100644 --- a/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/StopWatchTestExecutionListener.java +++ b/components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/StopWatchTestExecutionListener.java @@ -29,7 +29,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; */ public class StopWatchTestExecutionListener extends AbstractTestExecutionListener { - protected static ThreadLocal<StopWatch> threadStopWatch = new ThreadLocal<>(); + protected static final ThreadLocal<StopWatch> threadStopWatch = new ThreadLocal<>(); /** * Returns the precedence used by Spring to choose the appropriate execution order of test listeners. diff --git a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionMultipleIssueTest.java b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionMultipleIssueTest.java index f65f66cb8c5..e053780cd1a 100644 --- a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionMultipleIssueTest.java +++ b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionMultipleIssueTest.java @@ -16,8 +16,6 @@ */ package org.apache.camel.test.issues; -import org.apache.camel.Exchange; -import org.apache.camel.Processor; import org.apache.camel.builder.AdviceWith; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.component.mock.MockEndpoint; @@ -40,9 +38,7 @@ public class AdviceWithOnExceptionMultipleIssueTest extends CamelSpringTestSuppo @Test public void testSimpleMultipleAdvice() throws Exception { - AdviceWith.adviceWith(context, "RouteA", a -> { - a.interceptSendToEndpoint("mock:resultA").process(); - }); + AdviceWith.adviceWith(context, "RouteA", a -> a.interceptSendToEndpoint("mock:resultA").process()); AdviceWith.adviceWith(context, "RouteB", a -> { }); @@ -56,11 +52,9 @@ public class AdviceWithOnExceptionMultipleIssueTest extends CamelSpringTestSuppo @Test public void testMultipleAdviceWithExceptionThrown() throws Exception { - AdviceWith.adviceWith(context, "RouteA", a -> { - a.interceptSendToEndpoint("mock:resultA").process(e -> { - throw new Exception("my exception"); - }); - }); + AdviceWith.adviceWith(context, "RouteA", a -> a.interceptSendToEndpoint("mock:resultA").process(e -> { + throw new Exception("my exception"); + })); context.start(); @@ -74,11 +68,8 @@ public class AdviceWithOnExceptionMultipleIssueTest extends CamelSpringTestSuppo AdviceWith.adviceWith(context.getRouteDefinition("RouteA"), context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { - interceptSendToEndpoint("mock:resultA").process(new Processor() { - @Override - public void process(Exchange exchange) throws Exception { - throw new Exception("my exception"); - } + interceptSendToEndpoint("mock:resultA").process(exchange -> { + throw new Exception("my exception"); }); } }); diff --git a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionTransactedTest.java b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionTransactedTest.java index 0f8b9db59dd..2268df762e4 100644 --- a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionTransactedTest.java +++ b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionTransactedTest.java @@ -62,9 +62,8 @@ public class AdviceWithOnExceptionTransactedTest extends CamelSpringTestSupport @Test public void testAddFirstWithOnException() throws Exception { - AdviceWith.adviceWith(context, "advice-with-on-exception-transacted-test-route", a -> { - a.weaveAddFirst().transform(constant("Bye World")); - }); + AdviceWith.adviceWith(context, "advice-with-on-exception-transacted-test-route", + a -> a.weaveAddFirst().transform(constant("Bye World"))); context.start(); diff --git a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringProvidesBreakpointTest.java b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringProvidesBreakpointTest.java index a0ff67cf30a..8fa6f97bab4 100644 --- a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringProvidesBreakpointTest.java +++ b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringProvidesBreakpointTest.java @@ -25,6 +25,7 @@ import org.apache.camel.test.spring.junit5.ProvidesBreakpoint; 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.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,7 +48,7 @@ public class CamelSpringProvidesBreakpointTest assertNotNull(camelContext.getDebugger().getBreakpoints()); assertEquals(1, camelContext.getDebugger().getBreakpoints().size()); - assertTrue(camelContext.getDebugger().getBreakpoints().get(0) instanceof TestBreakpoint); + assertInstanceOf(TestBreakpoint.class, camelContext.getDebugger().getBreakpoints().get(0)); assertTrue(((TestBreakpoint) camelContext.getDebugger().getBreakpoints().get(0)).isBreakpointHit()); } diff --git a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringTestSupportTest.java b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringTestSupportTest.java index 128eb3079f5..e29eadcd2ae 100644 --- a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringTestSupportTest.java +++ b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringTestSupportTest.java @@ -42,9 +42,11 @@ public class CamelSpringTestSupportTest { byte[] buf = new byte[1024]; int l = tr.getInputStream().read(buf); String output = new String(buf, 0, l, StandardCharsets.UTF_8); - assertEquals("<camel id='camel-context-id'>\n" + - " <bean class='{{fooClass}}'/>\n" + - "</camel>\n", + assertEquals(""" + <camel id='camel-context-id'> + <bean class='{{fooClass}}'/> + </camel> + """, output); } } diff --git a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java index b73f8867c56..63d5c93e002 100644 --- a/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java +++ b/components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java @@ -17,9 +17,11 @@ package org.apache.camel.test.spring; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import org.apache.camel.test.spring.junit5.CamelSpringTestContextLoaderTestExecutionListener; +import org.apache.camel.test.spring.junit5.SpringTestExecutionListenerSorter; import org.apache.camel.test.spring.junit5.StopWatchTestExecutionListener; import org.junit.jupiter.api.Test; @@ -37,7 +39,7 @@ public class SpringTestExecutionListenerSorterTest { listenersInExpectedOrder.add(StopWatchTestExecutionListener.class); List<Class<?>> listenersSortedByPrecedence = new ArrayList<>(listenersInExpectedOrder); - listenersSortedByPrecedence.sort((c1, c2) -> Integer.compare(getPrecedence(c1), getPrecedence(c2))); + listenersSortedByPrecedence.sort(Comparator.comparingInt(SpringTestExecutionListenerSorter::getPrecedence)); assertEquals(listenersInExpectedOrder, listenersSortedByPrecedence); }