How to set a Camel exchangeProperty from a unit test

882 views Asked by At

I have a bunch of unit tests that run camel routes with code like

    // setup code here...
    String route = "direct:someroute";
    try (CamelContext context = new DefaultCamelContext()) {
        Object response = runCamelRoute(context, route, ci);
        checkResponse(route, response);
    }

but this route expects an exchange property to be set before it gets here - how can I set it? CamelContext has a whole lot of methods but I can't seem to find something like:

CamelRoute cr = context.getRoute(route);
cr.getExchange().setProperty("propertyName", "propetyValue");

Here is my camel run method for unit testing, with a bit of extra code for setting up an Oracle connection, etc.

protected Object runCamelRoute(CamelContext context, String route, Object message) throws Exception {
    context.addRoutes(new MyRouteBuilder() {
    });

    setupRegistry(context);
    context.start();

    FluentProducerTemplate template = context.createFluentProducerTemplate();
    template.withBody(message)
            .withHeader("hello", "goodbye") 
            .withProcessor(e -> e.setProperty("propertyName", "propertyValue")) // fail use header instead
            .to(route);

    try {
        Future<Object> future = template.asyncRequest();
        return future.get();
    } 
    catch(Exception ex) {
        System.out.println(route + " " + ex.getClass().getCanonicleName() + " " + ex.getMessage());
        throw ex;
    } 
    finally {
        template.stop();
        context.stop();
    }
}

private void setupRegistry(CamelContext context) {
    DataSource ds = DataSourceHelper.createConnectionPoolDev();
    context.getRegistry().bind("dataSource", ds);
    context.getRegistry().bind("Transformer", new Transformer());
}


public static OracleDataSource createConnectionPoolDev() {
    try {
        OracleDataSource ds = new OracleDataSource();
        ds.setConnectionCacheName("oraCache");
        ds.setURL("jdbc:oracle:thin:@//cluster:1521/server.domain.ca");
        ds.setUser("user");
        ds.setPassword("pass");
        return ds;
    } 
    catch (Exception ex) {
        logger.error("Failed to create connection to the database " + ex.getMessage());
    }
    return null;
}
1

There are 1 answers

0
TacheDeChoco On

Something like this may be ?

context.createFluentProducerTemplate()          
            .withBody(...)
            .withHeader(..., ...)
            .withProcessor( e -> e.setProperty(propertyName, propertyValue) )
            .to("direct:someroute")         
            .send();