user2753082
user2753082

Reputation: 41

Apache Camel Beans Unit Testing

I am using Apache Camel with Spring boot in my application. Currently I am working on a Unit test.

Java Code

Unit test

How do I mock

   .bean(DataService.class, "processData")

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?

Upvotes: 4

Views: 3175

Answers (2)

Abdelghani Roussi
Abdelghani Roussi

Reputation: 2817

This may seem's a late response, but I faced the same thing as described in your case, and I come across a simple way to "mock" the bean step, by using the DefaultRegistry to register the mocked bean into Camel registry, for example :

@Test
 public void shouldProcessData() throws Exception {
   ...
   ...
   DataService dataService = new DataService(...);
   stubBean("dataService", dataService); // put this before calling context.start();

   context.start();
   ...
   ...
}


/**
 * This method inject a stub bean into the registry
 * @param beanName the name of the bean being injected
 * @param instance the stub instance
 */
void stubBean(String beanName, Object instance) {
    DefaultRegistry registry = context.getRegistry(DefaultRegistry.class);
    registry.bind(beanName, instance);
}

Upvotes: 1

Liping Huang
Liping Huang

Reputation: 4476

You can autowired the DataService in your DataRoute like

@Component
public class DataRoute extends RouteBuilder {

    @Autowired
    private DataService dataService;

    @Override
    public void configure() throws Exception {
        from("direct:getData")
        .routeId("getData")
        .bean(dataService, "processData")
        .marshal().json(JsonLibrary.Jackson)
        .end();
    }

}

So you can mock the DataService as usual.

An alternative is using beanRef("beanName", "methodName") in the Route.

Upvotes: 0

Related Questions