camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Camel > Spring Testing
Date Fri, 02 Mar 2012 13:56:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/2042/9/1/_/styles/combined.css?spaceKey=CAMEL&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CAMEL/Spring+Testing">Spring
Testing</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~bvahdat">Babak
Vahdat</a>
    </h4>
        <br/>
                         <h4>Changes (1)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >h3. See Also <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >* <span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">a</span>
<span class="diff-added-words"style="background-color: #dfd;">A</span> [real example
test case using Mock and <span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">Spring|http://svn.apache.org/viewvc/camel/trunk/components/camel-spring/src/test/java/org/apache/camel/component/test/TestEndpointTest.java?view=markup]</span>
<span class="diff-added-words"style="background-color: #dfd;">Spring|https://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/mock/InterceptSendToMockEndpointStrategyTest.java]</span>
along with its [Spring <span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">XML|http://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/component/test/TestEndpointTest-context.xml]</span>
<span class="diff-added-words"style="background-color: #dfd;">XML|https://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/mock/InterceptSendToMockEndpointStrategyTest.xml]</span>
<br></td></tr>
            <tr><td class="diff-unchanged" >* [Bean Integration] <br>* [Mock]
endpoint <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="SpringTesting-SpringTesting"></a>Spring Testing</h2>

<p><a href="/confluence/display/CAMEL/Testing" title="Testing">Testing</a>
is a crucial part of any development or integration work. The Spring Framework offers a number
of features that makes it easy to test while using Spring for Inversion of Control which works
with JUnit 3.x, JUnit 4.x, and <a href="http://testng.org" class="external-link" rel="nofollow">TestNG</a>.</p>

<p>We can use Spring for IoC and the Camel <a href="/confluence/display/CAMEL/Mock"
title="Mock">Mock</a> and <a href="/confluence/display/CAMEL/Test" title="Test">Test</a>
endpoints to create sophisticated integration/unit tests that are easy to run and debug inside
your IDE. &nbsp;There are three supported approaches for testing with Spring in Camel.</p>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Name </th>
<th class='confluenceTh'> Testing Frameworks Supported </th>
<th class='confluenceTh'> Description </th>
<th class='confluenceTh'> Required Camel Test Dependencies </th>
</tr>
<tr>
<td class='confluenceTd'> CamelSpringTestSupport </td>
<td class='confluenceTd'><ul>
	<li>JUnit 3.x (deprecated)</li>
	<li>JUnit 4.x</li>
	<li>TestNG - <b>Camel 2.8</b></li>
</ul>
</td>
<td class='confluenceTd'> Provided by org.apache.camel.test.CamelSpringTestSupport,
org.apache.camel.test.junit4.CamelSpringTestSupport, and org.apache.camel.testng.CamelSpringTestSupport.
&nbsp;These base classes provide <a href="/confluence/display/CAMEL/Camel+Test#CamelTest-FeaturesProvidedbyCamelTestSupport">feature
parity</a> with&nbsp;the simple CamelTestSupport classes from&nbsp;<a href="/confluence/display/CAMEL/Camel+Test"
title="Camel Test">Camel Test</a>&nbsp;but do not support Spring annotations
on the test class such as <b>@Autowired</b>,&nbsp;<b>@DirtiesContext</b>,
and&nbsp;<b>@ContextConfiguration</b>. <br class="atl-forced-newline" />
</td>
<td class='confluenceTd'><ul>
	<li>JUnit 3.x (deprecated) - camel-test-spring</li>
	<li>JUnit 4.x&nbsp;&#45; camel-test-spring</li>
	<li>TestNG - camel-test-ng</li>
</ul>
</td>
</tr>
<tr>
<td class='confluenceTd'> Plain Spring Test <br class="atl-forced-newline" />
</td>
<td class='confluenceTd'><ul>
	<li>JUnit 3.x</li>
	<li>JUnit 4.x</li>
	<li>TestNG</li>
</ul>
</td>
<td class='confluenceTd'> Extend the abstract base classes (org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests,&nbsp;org.springframework.test.context.junit38.AbstractJUnit4SpringContextTests,
etc.)&nbsp;provided in Spring Test or use the Spring Test JUnit4 runner. &nbsp;These
approaches support both the Camel annotations and Spring annotations, but do not have <a
href="/confluence/display/CAMEL/Camel+Test#CamelTest-FeaturesProvidedbyCamelTestSupport">feature
parity</a> with&nbsp;org.apache.camel.test.CamelTestSupport, org.apache.camel.test.junit4.CamelTestSupport,
and org.apache.camel.testng.CamelSpringTestSupport. <br class="atl-forced-newline" />
</td>
<td class='confluenceTd'><ul>
	<li>JUnit 3.x (deprecated) - None</li>
	<li>JUnit 4.x&nbsp;&#45; None</li>
	<li>TestNG - None</li>
</ul>
</td>
</tr>
<tr>
<td class='confluenceTd'> Camel Enhanced Spring Test <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'><ul>
	<li>JUnit 4.x - <b>Camel 2.10</b></li>
	<li>TestNG - <b>Camel 2.10</b></li>
</ul>
</td>
<td class='confluenceTd'> Use the org.apache.camel.test.junit4.CamelSpringJUnit4ClassRunner&nbsp;runner
with the&nbsp;<b>@RunWith</b>&nbsp;annotation or extend org.apache.camel.testng.AbstractCamelTestNGSpringContextTests&nbsp;to
enable <a href="/confluence/display/CAMEL/Camel+Test#CamelTest-FeaturesProvidedbyCamelTestSupport">feature
parity</a> with org.apache.camel.test.CamelTestSupport and org.apache.camel.test.junit4.CamelTestSupport
and also support the full suite of Spring Test annotations such as&nbsp;<b>@Autowired</b>,&nbsp;<b>@DirtiesContext</b>,
and <b>@ContextConfiguration</b>. </td>
<td class='confluenceTd'><ul>
	<li>JUnit 3.x (deprecated) - camel-test-spring</li>
	<li>JUnit 4.x&nbsp;&#45; camel-test-spring</li>
	<li>TestNG - camel-test-ng</li>
</ul>
</td>
</tr>
</tbody></table>
</div>


<h3><a name="SpringTesting-CamelSpringTestSupport"></a>CamelSpringTestSupport</h3>

<p>org.apache.camel.test.CamelSpringTestSupport, org.apache.camel.test.junit4.CamelSpringTestSupport,
and org.apache.camel.testng.CamelSpringTestSupport&nbsp;extend their non-Spring aware
counterparts (org.apache.camel.test.CamelTestSupport, org.apache.camel.test.junit4.CamelTestSupport,
and org.apache.camel.testng.CamelTestSupport) and deliver integration with Spring into your
test classes. &nbsp;Instead of&nbsp;instantiating&nbsp;the CamelContext and routes
programmatically, these classes rely on a Spring context to wire the needed components together.
&nbsp;If your test extends one of these classes, you must provide the Spring context by
implementing the following method.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">protected</span> <span class="code-keyword">abstract</span>
AbstractApplicationContext createApplicationContext();
</pre>
</div></div>
<p>You are responsible for the instantiation of the Spring context in the method implementation.
&nbsp;All of the features available in the non-Spring aware counterparts from <a href="/confluence/display/CAMEL/Camel+Test"
title="Camel Test">Camel Test</a> are available in your test.</p>

<h3><a name="SpringTesting-PlainSpringTest"></a>Plain Spring Test</h3>

<p>In this approach, your test classes directly inherit from the Spring Test abstract
test classes or use the JUnit 4.x test runner provided in Spring Test. &nbsp;This approach
supports&nbsp;dependency&nbsp;injection into your test class and the full suite of
Spring Test annotations but does not support the features provided by the CamelSpringTestSupport
classes.</p>

<h4><a name="SpringTesting-PlainSpringTestusingJUnit3.xwithXMLConfigExample"></a>Plain
Spring Test using JUnit 3.x with XML Config Example</h4>

<p>Here is a simple unit test using JUnit 3.x support from Spring Test using&nbsp;<a
href="http://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/patterns/FilterTest.java"
class="external-link" rel="nofollow">XML Config</a>.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">@ContextConfiguration
<span class="code-keyword">public</span> class FilterTest <span class="code-keyword">extends</span>
AbstractJUnit38SpringContextTests {

    @EndpointInject(uri = <span class="code-quote">"mock:result"</span>)
    <span class="code-keyword">protected</span> MockEndpoint resultEndpoint;

    @Produce(uri = <span class="code-quote">"direct:start"</span>)
    <span class="code-keyword">protected</span> ProducerTemplate template;

    @DirtiesContext
    <span class="code-keyword">public</span> void testSendMatchingMessage() <span
class="code-keyword">throws</span> Exception {
        <span class="code-object">String</span> expectedBody = <span class="code-quote">"&lt;matched/&gt;"</span>;

        resultEndpoint.expectedBodiesReceived(expectedBody);

        template.sendBodyAndHeader(expectedBody, <span class="code-quote">"foo"</span>,
<span class="code-quote">"bar"</span>);

        resultEndpoint.assertIsSatisfied();
    }

    @DirtiesContext
    <span class="code-keyword">public</span> void testSendNotMatchingMessage()
<span class="code-keyword">throws</span> Exception {
        resultEndpoint.expectedMessageCount(0);

        template.sendBodyAndHeader(<span class="code-quote">"&lt;notMatched/&gt;"</span>,
<span class="code-quote">"foo"</span>, <span class="code-quote">"notMatchedHeaderValue"</span>);

        resultEndpoint.assertIsSatisfied();
    }
}
</pre>
</div></div>
<p>Notice that we use&nbsp;<b>@DirtiesContext</b>&nbsp;on the test
methods to force&nbsp;<a href="/confluence/display/CAMEL/Spring+Testing" title="Spring
Testing">Spring Testing</a>&nbsp;to automatically reload the&nbsp;<a href="/confluence/display/CAMEL/CamelContext"
title="CamelContext">CamelContext</a>&nbsp;after each test method - this ensures
that the tests don't clash with each other (e.g. one test method sending to an endpoint that
is then reused in another test method).</p>

<p>Also notice the use of&nbsp;<b>@ContextConfiguration</b>&nbsp;to
indicate that by default we should look for the&nbsp;<a href="http://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/patterns/FilterTest-context.xml"
class="external-link" rel="nofollow">FilterTest-context.xml on the classpath</a>&nbsp;to
configure the test case which looks like this</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">&lt;beans xmlns=<span class="code-quote">"http://www.springframework.org/schema/beans"</span>
       <span class="code-keyword">xmlns:xsi</span>=<span class="code-quote">"http://www.w3.org/2001/XMLSchema-instance"</span>
       <span class="code-keyword">xmlns:context</span>=<span class="code-quote">"http://www.springframework.org/schema/context"</span>
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    "&gt;

  <span class="code-tag">&lt;camelContext xmlns=<span class="code-quote">"http://camel.apache.org/schema/spring"</span>&gt;</span>
    <span class="code-tag">&lt;route&gt;</span>
      <span class="code-tag">&lt;from uri=<span class="code-quote">"direct:start"</span>/&gt;</span>
      <span class="code-tag">&lt;filter&gt;</span>
        <span class="code-tag">&lt;xpath&gt;</span>$foo = 'bar'<span
class="code-tag">&lt;/xpath&gt;</span>
        <span class="code-tag">&lt;to uri=<span class="code-quote">"mock:result"</span>/&gt;</span>
      <span class="code-tag">&lt;/filter&gt;</span>
    <span class="code-tag">&lt;/route&gt;</span>
  <span class="code-tag">&lt;/camelContext&gt;</span>

<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>
<p>This test will load a Spring XML configuration file calledFilterTest-context.xml&nbsp;from
the classpath in the same package structure as the FilterTest class and initialize it along
with any Camel routes we define inside it, then inject theCamelContextinstance into our test
case.</p>

<p>For instance, like this maven folder layout:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
src/test/java/org/apache/camel/spring/patterns/FilterTest.java
src/test/resources/org/apache/camel/spring/patterns/FilterTest-context.xml
</pre>
</div></div>

<h4><a name="SpringTesting-PlainSpringTestusingJUnit4.xwithJavaConfigExample"></a>Plain
Spring Test using JUnit 4.x with Java Config Example</h4>

<p>You can completely avoid using an XML configuration file by using <a href="/confluence/display/CAMEL/Spring+Java+Config"
title="Spring Java Config">Spring Java Config</a>. &nbsp;Here is a unit test
using JUnit 4.x support from Spring Test using&nbsp;<a href="http://svn.apache.org/repos/asf/camel/trunk/components/camel-spring-javaconfig/src/test/java/org/apache/camel/spring/javaconfig/patterns/FilterTest.java"
class="external-link" rel="nofollow">Java Config</a>.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">@ContextConfiguration(
        locations = <span class="code-quote">"org.apache.camel.spring.javaconfig.patterns.FilterTest$ContextConfig"</span>,
        loader = JavaConfigContextLoader.class)
<span class="code-keyword">public</span> class FilterTest <span class="code-keyword">extends</span>
AbstractJUnit4SpringContextTests {

    @EndpointInject(uri = <span class="code-quote">"mock:result"</span>)
    <span class="code-keyword">protected</span> MockEndpoint resultEndpoint;

    @Produce(uri = <span class="code-quote">"direct:start"</span>)
    <span class="code-keyword">protected</span> ProducerTemplate template;

    @DirtiesContext
    @Test
    <span class="code-keyword">public</span> void testSendMatchingMessage() <span
class="code-keyword">throws</span> Exception {
        <span class="code-object">String</span> expectedBody = <span class="code-quote">"&lt;matched/&gt;"</span>;

        resultEndpoint.expectedBodiesReceived(expectedBody);

        template.sendBodyAndHeader(expectedBody, <span class="code-quote">"foo"</span>,
<span class="code-quote">"bar"</span>);

        resultEndpoint.assertIsSatisfied();
    }

    @DirtiesContext
    @Test
    <span class="code-keyword">public</span> void testSendNotMatchingMessage()
<span class="code-keyword">throws</span> Exception {
        resultEndpoint.expectedMessageCount(0);

        template.sendBodyAndHeader(<span class="code-quote">"&lt;notMatched/&gt;"</span>,
<span class="code-quote">"foo"</span>, <span class="code-quote">"notMatchedHeaderValue"</span>);

        resultEndpoint.assertIsSatisfied();
    }

    @Configuration
    <span class="code-keyword">public</span> <span class="code-keyword">static</span>
class ContextConfig <span class="code-keyword">extends</span> SingleRouteCamelConfiguration
{
        @Bean
        <span class="code-keyword">public</span> RouteBuilder route() {
            <span class="code-keyword">return</span> <span class="code-keyword">new</span>
RouteBuilder() {
                <span class="code-keyword">public</span> void configure() {
                    from(<span class="code-quote">"direct:start"</span>).filter(header(<span
class="code-quote">"foo"</span>).isEqualTo(<span class="code-quote">"bar"</span>)).to(<span
class="code-quote">"mock:result"</span>);
                }
            };
        }
    }
}
</pre>
</div></div>

<p>This is similar to the XML Config example above except that there is no XML file
and instead the nested <b>ContextConfig</b> class does all of the configuration;
so your entire test case is contained in a single Java class. We currently have to reference
by class name this class in the <b>@ContextConfiguration</b> which is a bit ugly.
Please vote for <a href="http://jira.springframework.org/browse/SJC-238" class="external-link"
rel="nofollow">SJC-238</a> to address this and make Spring Test work more cleanly
with Spring JavaConfig.</p>

<h4><a name="SpringTesting-PlainSpringTestusingJUnit4.xRunnerwithXMLConfig"></a>Plain
Spring Test using JUnit 4.x Runner with XML Config</h4>

<p>You can avoid extending Spring classes by using the SpringJUnit4ClassRunner provided
by Spring Test. &nbsp;This custom JUnit runner means you are free to choose your own class
hierarchy while retaining all the capabilities of Spring Test.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
<span class="code-keyword">public</span> class MyCamelTest {

    @Autowired
    <span class="code-keyword">protected</span> CamelContext camelContext;

    @EndpointInject(uri = <span class="code-quote">"mock:foo"</span>)
    <span class="code-keyword">protected</span> MockEndpoint foo;


    @Test
    @DirtiesContext
    <span class="code-keyword">public</span> void testMocksAreValid() <span
class="code-keyword">throws</span> Exception {
        ...       

        foo.message(0).header(<span class="code-quote">"bar"</span>).isEqualTo(<span
class="code-quote">"ABC"</span>);

        MockEndpoint.assertIsSatisfied(camelContext);
    }
}
</pre>
</div></div>

<h3><a name="SpringTesting-CamelEnhancedSpringTest"></a>Camel Enhanced Spring
Test</h3>

<p>Using org.apache.camel.test.junit4.CamelSpringJUnit4ClassRunner&nbsp;runner with
the&nbsp;<b>@RunWith</b>&nbsp;annotation or extending org.apache.camel.testng.AbstractCamelTestNGSpringContextTests
provides the full feature set of Spring Test with support for the feature set provided in
the CamelTestSupport classes. &nbsp;A number of Camel specific annotations have been developed
in order to provide for declarative manipulation of the Camel context(s) involved in the test.
&nbsp;These annotations free your test classes from having to inherit from the CamelSpringTestSupport
classes and also reduce the amount of code required to customize the tests.\</p>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Annotation Class </th>
<th class='confluenceTh'> Applies To </th>
<th class='confluenceTh'> Description </th>
<th class='confluenceTh'> Default Behavioir If Not Present </th>
<th class='confluenceTh'> Default Behavior If Present </th>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.DisableJmx <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> Class </td>
<td class='confluenceTd'> Indicates if JMX should be globally disabled in the CamelContexts
that are bootstrapped &nbsp;during the test through the use of Spring Test loaded application
contexts. <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> JMX is disabled </td>
<td class='confluenceTd'> JMX is disabled <br class="atl-forced-newline" /> </td>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.ExcludeRoutes <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> Class <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Indicates if certain route builder classes should be excluded
from discovery. &nbsp;Initializes a org.apache.camel.spi.PackageScanClassResolver&nbsp;to
exclude a set of given classes from being resolved. Typically this is used at test time to
exclude certain routes,&nbsp;which might otherwise be just noisy, from being discovered
and initialized. <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Not enabled and no routes are excluded </td>
<td class='confluenceTd'> No routes are excluded </td>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.LazyLoadTypeConverters (Deprecated)
<br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Class <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Indicates if the&nbsp;CamelContexts that are bootstrapped
during the test through the use of Spring Test&nbsp;loaded application contexts should
use lazy loading of type converters. </td>
<td class='confluenceTd'> Type converters are not lazy loaded </td>
<td class='confluenceTd'> Type converters are not lazy loaded </td>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.MockEndpoints <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> Class <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Triggers the auto-mocking of endpoints whose URIs match the
provided filter.&nbsp; The default&nbsp;filter is "*" which matches all endpoints.
&nbsp;See&nbsp;org.apache.camel.impl.InterceptSendToMockEndpointStrategy&nbsp;for&nbsp;more
details on the registration of the mock endpoints. </td>
<td class='confluenceTd'> Not enabled </td>
<td class='confluenceTd'> All endpoints are sniffed and recorded in a mock endpoint.
</td>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.ProvidesBreakpoint <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> Method </td>
<td class='confluenceTd'> Indicates that the annotated method returns an&nbsp;org.apache.camel.spi.Breakpoint&nbsp;for
use in the test.&nbsp; Useful for intercepting&nbsp;traffic to all endpoints or simply
for setting a break point in an IDE for debugging.&nbsp; The method must&nbsp;be public,
static, take no arguments, and return org.apache.camel.spi.Breakpoint. <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> N/A </td>
<td class='confluenceTd'> The returned Breakpoint is registered in the CamelContext(s)
</td>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.ShutdownTimeout <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> Class <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Indicates to set the shutdown timeout of all CamelContexts
instantiated through the&nbsp;use of Spring Test loaded application contexts.&nbsp;
If no annotation is used, the timeout is&nbsp;automatically reduced to 10 seconds by the
test framework. <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> 10 seconds </td>
<td class='confluenceTd'> 10 seconds </td>
</tr>
<tr>
<td class='confluenceTd'> org.apache.camel.test.spring.UseAdviceWith <br class="atl-forced-newline"
/> </td>
<td class='confluenceTd'> Class <br class="atl-forced-newline" /> </td>
<td class='confluenceTd'> Indicates the use of adviceWith() within the test class.&nbsp;
If a class is annotated with&nbsp;this annotation and UseAdviceWith#value()&nbsp;returns
true, any&nbsp;CamelContexts bootstrapped during the test through the use of Spring Test
loaded&nbsp;application contexts will not be started automatically.&nbsp; The test
author is responsible for&nbsp;injecting the Camel contexts into the test and executing
CamelContext#start()&nbsp;on them&nbsp;at the appropriate time after any advice has
been applied to the routes in the CamelContext(s). <br class="atl-forced-newline" />
</td>
<td class='confluenceTd'> CamelContexts do not automatically start. </td>
<td class='confluenceTd'> CamelContexts do not automatically start. </td>
</tr>
</tbody></table>
</div>



<p>The following example illustrates the use of the <b>@MockEndpoints</b>&nbsp;annotation
in order to setup mock endpoints as interceptors on all endpoints using the Camel Log component
and the <b>@DisableJmx</b> annotation to enable JMX which is disabled during tests
by default. &nbsp;Note that we still use the <b>@DirtiesContext</b> annotation
to ensure that the CamelContext, routes, and mock endpoints are reinitialized between test
methods.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@RunWith(CamelSpringJUnit4ClassRunner.class)
@ContextConfiguration
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@MockEndpoints(<span class="code-quote">"log:*"</span>)
@DisableJmx(<span class="code-keyword">false</span>)
<span class="code-keyword">public</span> class CamelSpringJUnit4ClassRunnerPlainTest
{

    @Autowired
    <span class="code-keyword">protected</span> CamelContext camelContext2;

    <span class="code-keyword">protected</span> MockEndpoint mockB;

    @EndpointInject(uri = <span class="code-quote">"mock:c"</span>, context =
<span class="code-quote">"camelContext2"</span>)
    <span class="code-keyword">protected</span> MockEndpoint mockC;

    @Produce(uri = <span class="code-quote">"direct:start2"</span>, context =
<span class="code-quote">"camelContext2"</span>)
    <span class="code-keyword">protected</span> ProducerTemplate start2;

    @EndpointInject(uri = <span class="code-quote">"mock:log:org.apache.camel.test.junit4.spring"</span>,
context = <span class="code-quote">"camelContext2"</span>)
    <span class="code-keyword">protected</span> MockEndpoint mockLog;

    @Test
    <span class="code-keyword">public</span> void testPositive() <span class="code-keyword">throws</span>
Exception {

        mockC.expectedBodiesReceived(<span class="code-quote">"David"</span>);
        mockLog.expectedBodiesReceived(<span class="code-quote">"Hello David"</span>);

        start2.sendBody(<span class="code-quote">"David"</span>);

        MockEndpoint.assertIsSatisfied(camelContext);
    }
</pre>
</div></div>


<h3><a name="SpringTesting-AddingmoreMockexpectations"></a>Adding more Mock
expectations</h3>

<p>If you wish to programmatically add any new assertions to your test you can easily
do so with the following. Notice how we use @EndpointInject to inject a Camel endpoint into
our code then the <a href="/confluence/display/CAMEL/Mock" title="Mock">Mock</a>
API to add an expectation on a specific message.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@ContextConfiguration
<span class="code-keyword">public</span> class MyCamelTest <span class="code-keyword">extends</span>
AbstractJUnit38SpringContextTests {

    @Autowired
    <span class="code-keyword">protected</span> CamelContext camelContext;

    @EndpointInject(uri = <span class="code-quote">"mock:foo"</span>)
    <span class="code-keyword">protected</span> MockEndpoint foo;

    <span class="code-keyword">public</span> void testMocksAreValid() <span
class="code-keyword">throws</span> Exception {
        <span class="code-comment">// lets add more expectations
</span>        foo.message(0).header(<span class="code-quote">"bar"</span>).isEqualTo(<span
class="code-quote">"ABC"</span>);

        MockEndpoint.assertIsSatisfied(camelContext);
    }
}
</pre>
</div></div>

<h3><a name="SpringTesting-Furtherprocessingthereceivedmessages"></a>Further
processing the received messages</h3>

<p>Sometimes once a <a href="/confluence/display/CAMEL/Mock" title="Mock">Mock</a>
endpoint has received some messages you want to then process them further to add further assertions
that your test case worked as you expect.</p>

<p>So you can then process the received message exchanges if you like...</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@ContextConfiguration
<span class="code-keyword">public</span> class MyCamelTest <span class="code-keyword">extends</span>
AbstractJUnit38SpringContextTests {

    @Autowired
    <span class="code-keyword">protected</span> CamelContext camelContext;

    @EndpointInject(uri = <span class="code-quote">"mock:foo"</span>)
    <span class="code-keyword">protected</span> MockEndpoint foo;

    <span class="code-keyword">public</span> void testMocksAreValid() <span
class="code-keyword">throws</span> Exception {
        <span class="code-comment">// lets add more expectations...
</span>
        MockEndpoint.assertIsSatisfied(camelContext);

		<span class="code-comment">// now lets <span class="code-keyword">do</span>
some further assertions
</span>        List&lt;Exchange&gt; list = foo.getReceivedExchanges();
        <span class="code-keyword">for</span> (Exchange exchange : list) {
            Message in = exchange.getIn();
            ...
        }
    }
}
</pre>
</div></div>

<h3><a name="SpringTesting-Sendingandreceivingmessages"></a>Sending and
receiving messages</h3>

<p>It might be that the <a href="/confluence/display/CAMEL/Enterprise+Integration+Patterns"
title="Enterprise Integration Patterns">Enterprise Integration Patterns</a> you have
defined in either <a href="/confluence/display/CAMEL/Spring" title="Spring">Spring</a>
XML or using the Java <a href="/confluence/display/CAMEL/DSL" title="DSL">DSL</a>
do all of the sending and receiving and you might just  work with the <a href="/confluence/display/CAMEL/Mock"
title="Mock">Mock</a> endpoints as described above. However sometimes in a test case
its useful to explicitly send or receive messages directly.</p>

<p>To send or receive messages you should use the <a href="/confluence/display/CAMEL/Bean+Integration"
title="Bean Integration">Bean Integration</a> mechanism. For example to send messages
inject a ProducerTemplate using the @EndpointInject annotation then call the various send
methods on this object to send a message to an endpoint. To consume messages use the @MessageDriven
annotation on a method to have the method invoked when a message is received.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class Foo {
  @EndpointInject(uri=<span class="code-quote">"activemq:foo.bar"</span>)
  ProducerTemplate producer;

  <span class="code-keyword">public</span> void doSomething() {
    <span class="code-comment">// lets send a message!
</span>    producer.sendBody(<span class="code-quote">"&lt;hello&gt;world!&lt;/hello&gt;"</span>);
  }

  <span class="code-comment">// lets consume messages from the 'cheese' queue
</span>  @MessageDriven(uri=<span class="code-quote">"activemq:cheese"</span>)
  <span class="code-keyword">public</span> void onCheese(<span class="code-object">String</span>
name) {
    ...
  }
}
</pre>
</div></div>

<h3><a name="SpringTesting-SeeAlso"></a>See Also</h3>

<ul>
	<li>A <a href="https://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/mock/InterceptSendToMockEndpointStrategyTest.java"
class="external-link" rel="nofollow">real example test case using Mock and Spring</a>
along with its <a href="https://svn.apache.org/repos/asf/camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/mock/InterceptSendToMockEndpointStrategyTest.xml"
class="external-link" rel="nofollow">Spring XML</a></li>
	<li><a href="/confluence/display/CAMEL/Bean+Integration" title="Bean Integration">Bean
Integration</a></li>
	<li><a href="/confluence/display/CAMEL/Mock" title="Mock">Mock</a> endpoint</li>
	<li><a href="/confluence/display/CAMEL/Test" title="Test">Test</a> endpoint</li>
</ul>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/Spring+Testing">View
Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=76581&revisedVersion=21&originalVersion=20">View
Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/Spring+Testing?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message