How to unit test route with a bean that will access the database?

Here DB is just an example. This means that something cannot be prepared in the unit test environment.

Consider the route below:

DBBean dbBean = new DBBean();
from("direct:test").bean(dbBean).to("direct:someOtherLogic");

When unit test, is there any approach to mock "dbBean"? In unit test, it is difficult to install a real database.

Thank you for your help.

+5
source share
3 answers

Camel has a test kit that allows you to manage your route before testing. You can then keep the route intact, and then replace parts of the route and much more. Its a little more complicated and its documented as a tip - with functionality here: http://camel.apache.org/advicewith.html

, , EIP , - .

, , BeanDefinition, :

weaveByType(BeanDefinition.class).selectFirst().replace().to("mock:dbBean");

. , - Camel (, ) JAR.

, Camel Test Kit, , , .

+3

(DERBY ..)... , camel-jdbc unit test

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="timer://kickoff?period=10000"/>
        <setBody>
           <constant>select * from customer</constant>
        </setBody>
        <to uri="jdbc:testdb"/>
        <to uri="mock:result"/>
    </route>
 </camelContext>

  <!-- Just add a demo to show how to bind a date source for camel in Spring-->
  <jdbc:embedded-database id="testdb" type="DERBY">
      <jdbc:script location="classpath:sql/init.sql"/>
  </jdbc:embedded-database>

DBUnit ( ) Mockito ( )

+1

If your DbBean is an interface, then you can have two different implementations. One for the real work of the database. And others for bullying unit tests where you simulate a database.

Then it's just a matter of creating a layout in your unit test

DbBean db = new MockDbBean()

Like plain java code. In your RouteBuilder class you can use getter / setter

public class MyRouteBuilder extends RouteBuilder {
    private DbBean dbBean;

    // getter/setter for dbBean

   public void configure() throws Exception {
      from("direct:test").bean(dbBean).to("direct:someOtherLogic");
   }
}

Then from unit test you just need to install MockDbBean using the installer in the MyRouteBuilder instance.

+1
source

All Articles