简体   繁体   中英

Camel unit tests setting expectations on mock component

I am writing unit test cases using camel-test following steps outlined here . Under section Mocking existing endpoints using the camel-test component , there is a snippet

    getMockEndpoint("mock:direct:start").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:direct:foo").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye World");
    getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");

    template.sendBody("direct:start", "Hello World");

    assertMockEndpointsSatisfied();

I want to do something similar but my body type is a POJO without an overridden equals method.

I tried

getMockEndpoint("mock:result").message(0).method(new Object() {
    public boolean deepEquals(Exchange in) {
    MyPojo pojo = in.getIn().getBody(MyPojo.class); 

    return //custom pojo equals logic;
    }

}, "deepEquals").isEqualTo(true);

but am getting

Assertion error at index 0 on mock mock://result with predicate: BeanExpression[ method: deepEquals] == true evaluated as: null == true on Exchange[Message: MyPojo...]

The contents of the message is exactly as a I want however the test fails. Any advice would be appreciated. Thanks

Try this,

final MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expects(new Runnable() {
        public void run() {

            MyPojo myPojo = mock.getExchanges().get(0).getIn().getBody(MyPojo.class);
            boolean status = //custom pojo equals logic;
            if(!status){
                fail("Testcase fails");
            }
        }
    });

and another way,

mock.whenAnyExchangeReceived(new Processor() {
        public void process(Exchange exchange) throws Exception {

            MyPojo myPojo = exchange.getIn().getBody(MyPojo.class);
            boolean status =//custom pojo equals logic;

            exchange.getIn().setBody(status);
        }
    });
    boolean out = template.requestBody(url, new MyPojo(), Boolean.class);
    assertEquals(true, out);

Weird. I am getting the same error. There seems to be a bug in the reflection code where the bean expression is evaluated, probably due to this being an anonymous inner class.

Try this instead:

getMockEndpoint("mock:result").message(0).method(new Foo(), "deepEquals").isEqualTo(true);

And move the deepEquals method to named class public static class Foo in your test class somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM