Apache Camel - 测试日志消息

时间:2017-07-18 20:37:35

标签: unit-testing logging apache-camel

我正在尝试测试使用from(x).to(y).log("SuccessKey123")onException(HttpOperationFailedException.class).log("ErrorKey123")的Camel路线。

如何在成功处理消息时测试Camel记录“SuccessKey123”,或者如果抛出HttpOperationFailedException则记录“ErrorKey123”?

我的RouteBuilder():

@Component
public class myHttp4RouteBuilder extends SpringRouteBuilder {
    public static final ID = "foo";

    @Override
    public void configure() throws Exception {

        onException(HttpOperationFailedException.class)
                .log("ErrorKey123")
                .to(ERROR_QUEUE)
                .handled(true);

        from(AWS_SQS_ENDPOINT)
                .to(REST_API_ENDPOINT)
                .log("SuccessKey123");
    }
}

识别TestClass:

public class myHttp4RouteBuilderTest {

    @Produce(uri = MOCK_ROUTE_FROM)
    protected ProducerTemplate template;

    @EndpointInject(uri = MOCK_ROUTE_TO)
    private MockEndpoint mockEndpoint;

    @Autowired
    private CamelContext camelContext;

    @Before
    public void setup() throws Exception{
        RouteDefinition rd = camelContext.getRouteDefinition(myHttp4RouteBuilder.ID);
        rd.adviceWith(camelContext, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                replaceFromWith(MOCK_ROUTE_FROM);

                weaveByToUri(ERROR_QUEUE)
                        .replace()
                        .to(MOCK_ROUTE_TO);
            }
        });
    }

    @Test
    @DirtiesContext
    public void testSuccess() throws Exception {
            // throw an HttpOperationFailedException
        mockEndpoint.whenAnyExchangeReceived(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                throw new HttpOperationFailedException("Exception", 400, null, null, null, null);
            }
        });


        //
        //
        // How can I test here that camel logs "ErrorKey123"
        //
        //


        template.sendBody(MOCK_ROUTE_FROM, "some content");

        mockEndpoint.assertIsSatisfied();

    }
}

非常感谢!

3 个答案:

答案 0 :(得分:3)

Camel使用slf4j,所以你可以在设置时将一些测试appender添加到所需的记录器并检查之后记录的内容(甚至是模拟appender接口)

答案 1 :(得分:0)

您也可以使用Camel的建议,然后使用模拟等模拟/替换这些日志端点,然后断言Camel根据您的操作向这些人发送消息。

答案 2 :(得分:0)

我明白了;-)你让我走对了路。谢谢!

这是我的解决方案:

首先:创建一个自定义Appender

Parent()
Child()
object && subojbect
Child: [String:i_am_child, Int: 2]
Parent: [String: ]i_am_parent, Int: 1]
subojbect read access
i_am_parent
1

简短说明:使用append()方法,我们将每个日志事件添加到公共静态变量logEvents中。稍后在测试中我们可以访问logEvents。

让这个appender使用log4j有点困难。就我而言,我在测试资源package de.example.test; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.appender.AppenderLoggingException; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.layout.PatternLayout; import org.slf4j.event.LoggingEvent; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Plugin(name="myAppenderForTesting", category="Core", elementType="appender", printObject=true) public class MyAppenderForTesting extends AbstractAppender { /** Here we collect all log messages */ public static List<LogEvent> logEvents = new ArrayList<>(); protected MyAppenderForTesting(String name, Filter filter, Layout<? extends Serializable> layout, final boolean ignoreExceptions) { super(name, filter, layout, ignoreExceptions); } @PluginFactory public static MyAppenderForTesting createAppender( @PluginAttribute("name") String name, @PluginElement("Layout") Layout<? extends Serializable> layout, @PluginElement("Filter") final Filter filter, @PluginAttribute("otherAttribute") String otherAttribute) { return new MyAppenderForTesting(name, filter, layout, true); } @Override public void append(LogEvent event) { try { logEvents.add(event); } catch (Exception ex) { if (!ignoreExceptions()) { throw new AppenderLoggingException(ex); } } finally { } } /** * Clear log messages */ public static void clean() { logEvents.clear(); } } 中创建了log4j2.xml

src\test\resources\log4j2.xml

在我的测试课程中,我可以直接访问<?xml version="1.0" encoding="UTF-8" ?> <Configuration packages="de.example"> <Appenders> <myAppenderForTesting name="myAppenderForTesting"> <PatternLayout alwaysWriteExceptions="false" pattern="%d{dd.MM.yyyy HH:mm:ss} %-5p %t [%C{1}.%M:%L] %m %ex{10000}%n" /> </myAppenderForTesting> </Appenders> <Loggers> <Root level="INFO"> <AppenderRef ref="myAppenderForTesting"/> </Root> </Loggers> </Configuration> 。例如

MyAppenderForTesting.logEvents