Class CamelTestSupport
- java.lang.Object
-
- org.apache.camel.test.junit5.CamelTestSupport
-
- All Implemented Interfaces:
org.junit.jupiter.api.extension.AfterAllCallback,org.junit.jupiter.api.extension.AfterEachCallback,org.junit.jupiter.api.extension.AfterTestExecutionCallback,org.junit.jupiter.api.extension.BeforeAllCallback,org.junit.jupiter.api.extension.BeforeEachCallback,org.junit.jupiter.api.extension.BeforeTestExecutionCallback,org.junit.jupiter.api.extension.Extension
- Direct Known Subclasses:
EndpointUriFactoryTestSupport,ExchangeTestSupport
public abstract class CamelTestSupport extends Object implements org.junit.jupiter.api.extension.BeforeEachCallback, org.junit.jupiter.api.extension.AfterEachCallback, org.junit.jupiter.api.extension.AfterAllCallback, org.junit.jupiter.api.extension.BeforeAllCallback, org.junit.jupiter.api.extension.BeforeTestExecutionCallback, org.junit.jupiter.api.extension.AfterTestExecutionCallback
A useful base class which creates aCamelContextwith some routes along with aProducerTemplatefor use in the test case Do not use this class for Spring Boot testing.
-
-
Field Summary
Fields Modifier and Type Field Description protected org.apache.camel.ServicecamelContextServiceprotected CamelTestSupportcamelTestSupportExtensionprotected org.apache.camel.ConsumerTemplateconsumerprotected org.apache.camel.model.ModelCamelContextcontextprotected Propertiesextraprotected org.apache.camel.FluentProducerTemplatefluentTemplatestatic StringROUTE_COVERAGE_ENABLEDJVM system property which can be set to true to turn on dumping route coverage statistics.protected org.apache.camel.ProducerTemplatetemplate
-
Constructor Summary
Constructors Constructor Description CamelTestSupport()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidafterAll(org.junit.jupiter.api.extension.ExtensionContext context)voidafterEach(org.junit.jupiter.api.extension.ExtensionContext context)voidafterTestExecution(org.junit.jupiter.api.extension.ExtensionContext context)protected voidapplyCamelPostProcessor()Applies theCamelBeanPostProcessorto this instance.protected voidassertExpression(org.apache.camel.Exchange exchange, String languageName, String expressionText, Object expectedValue)Asserts that the given language name and expression evaluates to the given value on a specific exchangeprotected voidassertMockEndpointsSatisfied()Asserts that all the expectations of the Mock endpoints are validprotected voidassertMockEndpointsSatisfied(long timeout, TimeUnit unit)Asserts that all the expectations of the Mock endpoints are validprotected voidassertPredicate(String languageName, String expressionText, org.apache.camel.Exchange exchange, boolean expected)Asserts that the given language name and predicate expression evaluates to the expected value on the message exchangeprotected org.apache.camel.spi.LanguageassertResolveLanguage(String languageName)Asserts that the language name can be resolvedprotected voidassertValidContext(org.apache.camel.CamelContext context)voidbeforeAll(org.junit.jupiter.api.extension.ExtensionContext context)voidbeforeEach(org.junit.jupiter.api.extension.ExtensionContext context)voidbeforeTestExecution(org.junit.jupiter.api.extension.ExtensionContext context)protected voidbindToRegistry(org.apache.camel.spi.Registry registry)Allows to bind custom beans to the CamelRegistry.org.apache.camel.ServicecamelContextService()protected voidcleanupResources()Strategy to perform resources cleanup, afterCamelContextis stoppedorg.apache.camel.ConsumerTemplateconsumer()org.apache.camel.CamelContextcontext()protected org.apache.camel.CamelContextcreateCamelContext()protected org.apache.camel.spi.RegistrycreateCamelRegistry()Override to use a customRegistry.protected org.apache.camel.ExchangecreateExchangeWithBody(Object body)Creates an exchange with the given bodyprotected org.apache.camel.RoutesBuildercreateRouteBuilder()Factory method which derived classes can use to create aRouteBuilderto define the routes for testingprotected org.apache.camel.RoutesBuilder[]createRouteBuilders()Factory method which derived classes can use to create an array ofRouteBuilders to define the routes for testingprotected voiddebugAfter(org.apache.camel.Exchange exchange, org.apache.camel.Processor processor, org.apache.camel.model.ProcessorDefinition<?> definition, String id, String label, long timeTaken)Single step debugs and Camel invokes this method after processing the given processorprotected voiddebugBefore(org.apache.camel.Exchange exchange, org.apache.camel.Processor processor, org.apache.camel.model.ProcessorDefinition<?> definition, String id, String label)Single step debugs and Camel invokes this method before entering the given processorvoiddeleteTestDirectory()protected voiddisableJMX()Disables the JMX agent.protected voiddoPostSetup()Strategy to perform any post setup afterCamelContextis createdprotected voiddoPostTearDown()Strategy to perform any post action, afterCamelContextis stoppedprotected voiddoPreSetup()Strategy to perform any pre setup, beforeCamelContextis createdprotected voiddoQuarkusCheck()Detects if this is a Camel-quarkus test and throw an exception, as these base classes is not intended for testing Camel onQuarkus.protected voiddoSetUp()protected voiddoSpringBootCheck()Detects if this is a Spring-Boot test and throws an exception, as these base classes is not intended for testing Camel on Spring Boot.protected voiddoStopCamelContext(org.apache.camel.CamelContext context, org.apache.camel.Service camelContextService)protected voidenableJMX()Enables the JMX agent.protected StringfileUri()protected StringfileUri(String query)org.apache.camel.FluentProducerTemplatefluentTemplate()org.apache.camel.ServicegetCamelContextService()StringgetCurrentTestName()Gets the name of the current test being executed.protected org.apache.camel.EndpointgetMandatoryEndpoint(String uri)protected <T extends org.apache.camel.Endpoint>
TgetMandatoryEndpoint(String uri, Class<T> type)protected org.apache.camel.component.mock.MockEndpointgetMockEndpoint(String uri)Resolves the mandatory Mock endpoint using a URI of the formmock:someNameprotected org.apache.camel.component.mock.MockEndpointgetMockEndpoint(String uri, boolean create)Resolves theMockEndpointusing a URI of the formmock:someName, optionally creating it if it does not exist.StringgetRouteFilterExcludePattern()Used for filtering routes matching the given pattern, which follows the following rules:StringgetRouteFilterIncludePattern()Used for filtering routes matching the given pattern, which follows the following rules:protected intgetShutdownTimeout()Returns the timeout to use when shutting down (unit in seconds).protected booleanhasClassAnnotation(String... names)Does this test class have any of the following annotations on the class-level.protected BooleanignoreMissingLocationWithPropertiesComponent()Whether to ignore missing locations with thePropertiesComponent.booleanisCreateCamelContextPerClass()Tells whetherCamelContextshould be setup per test or per class.booleanisDumpRouteCoverage()Whether to dump route coverage stats at the end of the test.StringisMockEndpoints()Override to enable auto mocking endpoints based on the pattern.StringisMockEndpointsAndSkip()Override to enable auto mocking endpoints based on the pattern, and skip sending to original endpoint.booleanisUseAdviceWith()Override when using advice with and return true.booleanisUseDebugger()Override to enable debuggerbooleanisUseRouteBuilder()Use the RouteBuilder or notprotected voidpostProcessTest()voidreplaceRouteFromWith(String routeId, String fromEndpoint)protected voidresetMocks()Reset all Mock endpoints.protected org.apache.camel.EndpointresolveMandatoryEndpoint(String uri)Resolves a mandatory endpoint for the given URI or an exception is thrownprotected <T extends org.apache.camel.Endpoint>
TresolveMandatoryEndpoint(String uri, Class<T> endpointType)Resolves a mandatory endpoint for the given URI and expected type or an exception is thrownprotected voidsendBodies(String endpointUri, Object... bodies)Sends messages to the given endpoint for each of the specified bodiesprotected voidsendBody(String endpointUri, Object body)Sends a message to the given endpoint URI with the body valueprotected voidsendBody(String endpointUri, Object body, Map<String,Object> headers)Sends a message to the given endpoint URI with the body value and specified headersvoidsetCamelContextService(org.apache.camel.Service service)Allows a service to be registered a separate lifecycle service to start and stop the context; such as for Spring when the ApplicationContext is started and stopped, rather than directly stopping the CamelContextvoidsetUp()protected voidsetupResources()Strategy to perform resources setup, beforeCamelContextis createdvoidsetUseRouteBuilder(boolean useRouteBuilder)protected voidstartCamelContext()protected voidstopCamelContext()voidtearDown()org.apache.camel.ProducerTemplatetemplate()protected PathtestDirectory()protected PathtestDirectory(boolean create)static PathtestDirectory(Class<?> testClass, boolean create)protected PathtestDirectory(String dir)protected PathtestDirectory(String dir, boolean create)protected PathtestFile(String dir)longtimeTaken()protected booleanuseJmx()Whether or not JMX should be used during testing.protected PropertiesuseOverridePropertiesWithPropertiesComponent()Override this method to include and override properties with the CamelPropertiesComponent.
-
-
-
Field Detail
-
ROUTE_COVERAGE_ENABLED
public static final String ROUTE_COVERAGE_ENABLED
JVM system property which can be set to true to turn on dumping route coverage statistics.- See Also:
- Constant Field Values
-
extra
protected Properties extra
-
context
protected volatile org.apache.camel.model.ModelCamelContext context
-
template
protected volatile org.apache.camel.ProducerTemplate template
-
fluentTemplate
protected volatile org.apache.camel.FluentProducerTemplate fluentTemplate
-
consumer
protected volatile org.apache.camel.ConsumerTemplate consumer
-
camelContextService
protected volatile org.apache.camel.Service camelContextService
-
camelTestSupportExtension
@RegisterExtension protected CamelTestSupport camelTestSupportExtension
-
-
Method Detail
-
afterTestExecution
public void afterTestExecution(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception- Specified by:
afterTestExecutionin interfaceorg.junit.jupiter.api.extension.AfterTestExecutionCallback- Throws:
Exception
-
beforeTestExecution
public void beforeTestExecution(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception- Specified by:
beforeTestExecutionin interfaceorg.junit.jupiter.api.extension.BeforeTestExecutionCallback- Throws:
Exception
-
timeTaken
public long timeTaken()
-
beforeEach
public void beforeEach(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception- Specified by:
beforeEachin interfaceorg.junit.jupiter.api.extension.BeforeEachCallback- Throws:
Exception
-
afterEach
public void afterEach(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception- Specified by:
afterEachin interfaceorg.junit.jupiter.api.extension.AfterEachCallback- Throws:
Exception
-
beforeAll
public void beforeAll(org.junit.jupiter.api.extension.ExtensionContext context)
- Specified by:
beforeAllin interfaceorg.junit.jupiter.api.extension.BeforeAllCallback
-
afterAll
public void afterAll(org.junit.jupiter.api.extension.ExtensionContext context)
- Specified by:
afterAllin interfaceorg.junit.jupiter.api.extension.AfterAllCallback
-
isUseRouteBuilder
public boolean isUseRouteBuilder()
Use the RouteBuilder or not- Returns:
- true then
CamelContextwill be auto started, false thenCamelContextwill not be auto started (you will have to start it manually)
-
setUseRouteBuilder
public void setUseRouteBuilder(boolean useRouteBuilder)
-
isDumpRouteCoverage
public boolean isDumpRouteCoverage()
Whether to dump route coverage stats at the end of the test. This allows tooling or manual inspection of the stats, so you can generate a route trace diagram of which EIPs have been in use and which have not. Similar concepts as a code coverage report. You can also turn on route coverage globally via setting JVM system property CamelTestRouteCoverage=true.- Returns:
- true to write route coverage status in an xml file in the target/camel-route-coverage directory after the test has finished.
-
isUseAdviceWith
public boolean isUseAdviceWith()
Override when using advice with and return true. This helps knowing advice with is to be used, andCamelContextwill not be started before the advice with takes place. This helps by ensuring the advice with has been property setup before theCamelContextis started Important: Its important to startCamelContextmanually from the unit test after you are done doing all the advice with.- Returns:
- true if you use advice with in your unit tests.
-
isCreateCamelContextPerClass
public final boolean isCreateCamelContextPerClass()
Tells whetherCamelContextshould be setup per test or per class. By default it will be setup/teardown per test method. This method returnstruewhen the camel test class is annotated with @TestInstance(TestInstance.Lifecycle.PER_CLASS). Important: Use this with care as theCamelContextwill carry over state from previous tests, such as endpoints, components etc. So you cannot use this in all your tests. Setting upCamelContextuses thedoPreSetup(),doSetUp(), anddoPostSetup()methods in that given order.- Returns:
- true per class, false per test.
-
isMockEndpoints
public String isMockEndpoints()
Override to enable auto mocking endpoints based on the pattern. Return * to mock all endpoints.- See Also:
EndpointHelper.matchEndpoint(CamelContext, String, String)
-
isMockEndpointsAndSkip
public String isMockEndpointsAndSkip()
Override to enable auto mocking endpoints based on the pattern, and skip sending to original endpoint. Return * to mock all endpoints.- See Also:
EndpointHelper.matchEndpoint(CamelContext, String, String)
-
getRouteFilterIncludePattern
public String getRouteFilterIncludePattern()
Used for filtering routes matching the given pattern, which follows the following rules:- Match by route id - Match by route input endpoint uri
The matching is using exact match, by wildcard and regular expression.
For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:*
Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar*
Exclude takes precedence over include.
-
getRouteFilterExcludePattern
public String getRouteFilterExcludePattern()
Used for filtering routes matching the given pattern, which follows the following rules:- Match by route id - Match by route input endpoint uri
The matching is using exact match, by wildcard and regular expression.
For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:*
Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar*
Exclude takes precedence over include.
-
getCurrentTestName
public final String getCurrentTestName()
Gets the name of the current test being executed.
-
isUseDebugger
public boolean isUseDebugger()
Override to enable debugger Is default false
-
getCamelContextService
public org.apache.camel.Service getCamelContextService()
-
camelContextService
public org.apache.camel.Service camelContextService()
-
context
public org.apache.camel.CamelContext context()
-
template
public org.apache.camel.ProducerTemplate template()
-
fluentTemplate
public org.apache.camel.FluentProducerTemplate fluentTemplate()
-
consumer
public org.apache.camel.ConsumerTemplate consumer()
-
setCamelContextService
public void setCamelContextService(org.apache.camel.Service service)
Allows a service to be registered a separate lifecycle service to start and stop the context; such as for Spring when the ApplicationContext is started and stopped, rather than directly stopping the CamelContext
-
doPreSetup
protected void doPreSetup() throws ExceptionStrategy to perform any pre setup, beforeCamelContextis created- Throws:
Exception
-
doPostSetup
protected void doPostSetup() throws ExceptionStrategy to perform any post setup afterCamelContextis created- Throws:
Exception
-
doSpringBootCheck
protected void doSpringBootCheck()
Detects if this is a Spring-Boot test and throws an exception, as these base classes is not intended for testing Camel on Spring Boot.
-
doQuarkusCheck
protected void doQuarkusCheck()
Detects if this is a Camel-quarkus test and throw an exception, as these base classes is not intended for testing Camel onQuarkus.
-
doPostTearDown
protected void doPostTearDown() throws ExceptionStrategy to perform any post action, afterCamelContextis stopped- Throws:
Exception
-
setupResources
protected void setupResources() throws ExceptionStrategy to perform resources setup, beforeCamelContextis created- Throws:
Exception
-
cleanupResources
protected void cleanupResources() throws ExceptionStrategy to perform resources cleanup, afterCamelContextis stopped- Throws:
Exception
-
getShutdownTimeout
protected int getShutdownTimeout()
Returns the timeout to use when shutting down (unit in seconds). Will default use 10 seconds.- Returns:
- the timeout to use
-
useJmx
protected boolean useJmx()
Whether or not JMX should be used during testing.- Returns:
- false by default.
-
useOverridePropertiesWithPropertiesComponent
protected Properties useOverridePropertiesWithPropertiesComponent()
Override this method to include and override properties with the CamelPropertiesComponent.- Returns:
- additional properties to add/override.
-
ignoreMissingLocationWithPropertiesComponent
protected Boolean ignoreMissingLocationWithPropertiesComponent()
Whether to ignore missing locations with thePropertiesComponent. For example when unit testing you may want to ignore locations that are not available in the environment used for testing.- Returns:
- true to ignore, false to not ignore, and null to leave as configured on the
PropertiesComponent
-
applyCamelPostProcessor
protected void applyCamelPostProcessor() throws ExceptionApplies theCamelBeanPostProcessorto this instance.Derived classes using IoC / DI frameworks may wish to turn this into a NoOp such as for CDI we would just use CDI to inject this
- Throws:
Exception
-
hasClassAnnotation
protected boolean hasClassAnnotation(String... names)
Does this test class have any of the following annotations on the class-level.
-
doStopCamelContext
protected void doStopCamelContext(org.apache.camel.CamelContext context, org.apache.camel.Service camelContextService)
-
createCamelContext
protected org.apache.camel.CamelContext createCamelContext() throws Exception- Throws:
Exception
-
bindToRegistry
protected void bindToRegistry(org.apache.camel.spi.Registry registry) throws ExceptionAllows to bind custom beans to the CamelRegistry.- Throws:
Exception
-
createCamelRegistry
protected org.apache.camel.spi.Registry createCamelRegistry() throws ExceptionOverride to use a customRegistry.However if you need to bind beans to the registry then this is possible already with the bind method on registry, and there is no need to override this method.
- Throws:
Exception
-
createRouteBuilder
protected org.apache.camel.RoutesBuilder createRouteBuilder() throws ExceptionFactory method which derived classes can use to create aRouteBuilderto define the routes for testing- Throws:
Exception
-
createRouteBuilders
protected org.apache.camel.RoutesBuilder[] createRouteBuilders() throws ExceptionFactory method which derived classes can use to create an array ofRouteBuilders to define the routes for testing- Throws:
Exception- See Also:
createRouteBuilder()
-
resolveMandatoryEndpoint
protected org.apache.camel.Endpoint resolveMandatoryEndpoint(String uri)
Resolves a mandatory endpoint for the given URI or an exception is thrown- Parameters:
uri- the Camel URI to use to create or resolve an endpoint- Returns:
- the endpoint
-
resolveMandatoryEndpoint
protected <T extends org.apache.camel.Endpoint> T resolveMandatoryEndpoint(String uri, Class<T> endpointType)
Resolves a mandatory endpoint for the given URI and expected type or an exception is thrown- Parameters:
uri- the Camel URI to use to create or resolve an endpoint- Returns:
- the endpoint
-
getMockEndpoint
protected org.apache.camel.component.mock.MockEndpoint getMockEndpoint(String uri)
Resolves the mandatory Mock endpoint using a URI of the formmock:someName- Parameters:
uri- the URI which typically starts with "mock:" and has some name- Returns:
- the mandatory mock endpoint or an exception is thrown if it could not be resolved
-
getMockEndpoint
protected org.apache.camel.component.mock.MockEndpoint getMockEndpoint(String uri, boolean create) throws org.apache.camel.NoSuchEndpointException
Resolves theMockEndpointusing a URI of the formmock:someName, optionally creating it if it does not exist. This implementation will lookup existing mock endpoints and match on the mock queue name, eg mock:foo and mock:foo?retainFirst=5 would match as the queue name is foo.- Parameters:
uri- the URI which typically starts with "mock:" and has some namecreate- whether or not to allow the endpoint to be created if it doesn't exist- Returns:
- the mock endpoint or an
NoSuchEndpointExceptionis thrown if it could not be resolved - Throws:
org.apache.camel.NoSuchEndpointException- is the mock endpoint does not exists
-
sendBody
protected void sendBody(String endpointUri, Object body)
Sends a message to the given endpoint URI with the body value- Parameters:
endpointUri- the URI of the endpoint to send tobody- the body for the message
-
sendBody
protected void sendBody(String endpointUri, Object body, Map<String,Object> headers)
Sends a message to the given endpoint URI with the body value and specified headers- Parameters:
endpointUri- the URI of the endpoint to send tobody- the body for the messageheaders- any headers to set on the message
-
sendBodies
protected void sendBodies(String endpointUri, Object... bodies)
Sends messages to the given endpoint for each of the specified bodies- Parameters:
endpointUri- the endpoint URI to send tobodies- the bodies to send, one per message
-
createExchangeWithBody
protected org.apache.camel.Exchange createExchangeWithBody(Object body)
Creates an exchange with the given body
-
assertExpression
protected void assertExpression(org.apache.camel.Exchange exchange, String languageName, String expressionText, Object expectedValue)Asserts that the given language name and expression evaluates to the given value on a specific exchange
-
assertPredicate
protected void assertPredicate(String languageName, String expressionText, org.apache.camel.Exchange exchange, boolean expected)
Asserts that the given language name and predicate expression evaluates to the expected value on the message exchange
-
assertResolveLanguage
protected org.apache.camel.spi.Language assertResolveLanguage(String languageName)
Asserts that the language name can be resolved
-
assertMockEndpointsSatisfied
protected void assertMockEndpointsSatisfied() throws InterruptedExceptionAsserts that all the expectations of the Mock endpoints are valid- Throws:
InterruptedException
-
assertMockEndpointsSatisfied
protected void assertMockEndpointsSatisfied(long timeout, TimeUnit unit) throws InterruptedExceptionAsserts that all the expectations of the Mock endpoints are valid- Throws:
InterruptedException
-
resetMocks
protected void resetMocks()
Reset all Mock endpoints.
-
assertValidContext
protected void assertValidContext(org.apache.camel.CamelContext context)
-
getMandatoryEndpoint
protected <T extends org.apache.camel.Endpoint> T getMandatoryEndpoint(String uri, Class<T> type)
-
getMandatoryEndpoint
protected org.apache.camel.Endpoint getMandatoryEndpoint(String uri)
-
disableJMX
protected void disableJMX()
Disables the JMX agent. Must be called before thesetUp()method.
-
enableJMX
protected void enableJMX()
Enables the JMX agent. Must be called before thesetUp()method.
-
debugBefore
protected void debugBefore(org.apache.camel.Exchange exchange, org.apache.camel.Processor processor, org.apache.camel.model.ProcessorDefinition<?> definition, String id, String label)Single step debugs and Camel invokes this method before entering the given processor
-
debugAfter
protected void debugAfter(org.apache.camel.Exchange exchange, org.apache.camel.Processor processor, org.apache.camel.model.ProcessorDefinition<?> definition, String id, String label, long timeTaken)Single step debugs and Camel invokes this method after processing the given processor
-
testDirectory
protected Path testDirectory()
-
testDirectory
protected Path testDirectory(boolean create)
-
fileUri
protected String fileUri()
-
deleteTestDirectory
public void deleteTestDirectory()
-
-