title: Apache Camel Beans Unit Testing
body: <p>I am using Apache Camel with Spring boot in my application. Currently I am working on a Unit test.</p>
  
  <p>Java Code</p>
  
  <ul>
  <li><p>DataRoute class</p>
  
  <pre><code>from("direct:getData")
  .routeId("getData")
  .bean(DataService.class, "processData")
  .marshal().json(JsonLibrary.Jackson)
  .end();
  </code></pre></li>
  <li><p>DataService class</p>
  
  <pre><code>public Data processData() {
      return new Data("Hello World");
  }
  </code></pre></li>
  <li><p>Data Class with getters, setters and Jackson toString method</p>
  
  <pre><code>private String value;
  </code></pre></li>
  </ul>
  
  <p>Unit test</p>
  
  <ul>
  <li><p>BaseCamelContextUnitText</p>
  
  <pre><code>public abstract class BaseCamelContextUnitTest extends CamelTestSupport
  {
       @Autowired
       private DataService dataService;
  
       @Produce
       private ProducerTemplate producerTemplate;
  
       public CamelContext getCamelContext() {
           return camelContext;
       } 
  
       @Override
       protected Context createJndiContext() throws Exception {
           JndiContext context = new JndiContext();
           context.bind("dataService", dataService);
           return context;
       }
  
       @Test
       public void shouldProcessData() throws Exception {
            RouteDefinition routeDef = getCamelContext().getRouteDefinition("getData");
            routeDef.adviceWith((ModelCamelContext) getCamelContext(), new RouteBuilder() {
  
               @Override
               public void configure() throws Exception {
                    from("direct:getData")
                      .pipeline("bean:dataService?method=processData");
               }
       });
  
       getCamelContext().start();
  
       String responseData = "{"
          + "\"value\":\"Unit test success\""
          + "}";
  
       Object response = producerTemplate.sendBody("direct:getData",   ExchangePattern.InOut, null);
  
       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  ((InputStreamCache) response).writeTo(byteArrayOutputStream);
  
       assertThat(new String(byteArrayOutputStream.toByteArray()), is(responseData));
       }
    }
  </code></pre></li>
  </ul>
  
  <p>How do I mock</p>
  
  <pre><code>   .bean(DataService.class, "processData")
  </code></pre>
  
  <p>in the unit test to return a mock Data Object with its default String variable as say "Unit test success" and then test to see if the route would give back the mocked Object instead of the Object with "Hello World" String variable?</p>