如何模拟WS客户端并在camel路由中提供响应

时间:2014-09-15 20:38:17

标签: web-services unit-testing apache-camel

我想在驼峰路线中模拟WS客户端调用,检查请求并提供响应。

这是一个测试

package com.example.helloworld;

import org.apache.camel.*;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author deveproject
 * @version 9/15/14
 */
public class WsClientMockTest extends CamelSpringTestSupport {

    @Produce(uri = "direct:test-ws-client-mock")
    protected ProducerTemplate template;

    @Override
    public String isMockEndpoints() {
        return "cxf:bean:greeterService";
    }

    @Test
    public void testGetActionRoute() throws Exception {
        MockEndpoint greeterService = getMockEndpoint("mock:cxf:bean:greeterService");

        greeterService.expectedMessagesMatches(new Predicate() {

            @Override
            public boolean matches(Exchange exchange) {
                assertEquals("U.S.", exchange.getIn().getBody(String.class));
                return true;
            }
        });
        template.sendBody("U.S.");


        greeterService.assertIsSatisfied();
    }

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("META-INF/spring/camel-context.xml");
    }
}

org.apache.camel.Predicate检查请求是否正确。 我找不到如何提供回复的方法。

我有以上测试的工作示例。我可以按要求发布它。

谢谢。

1 个答案:

答案 0 :(得分:4)

您可以使用 returnReplyBody(Expession expression)方法进行模拟回复。

参见示例:

@Test
public void testGetActionRoute() throws Exception {
    MockEndpoint greeterService = getMockEndpoint("mock:cxf:bean:greeterService");

    greeterService.returnReplyBody(new Expression() {
        @Override
        public <T> T evaluate(Exchange exchange, Class<T> type) {
            GreeterServiceResponse response = new GreeterServiceResponseResponse();
            response.setGreeting("Hello!");
            return (T) response;
        }
    });

    greeterService.expectedMessagesMatches(new Predicate() {

        @Override
        public boolean matches(Exchange exchange) {
            assertEquals("U.S.", exchange.getIn().getBody(String.class));
            return true;
        }
    });
    template.sendBody("U.S.");


    greeterService.assertIsSatisfied();
}