如何对Consumer <headerspec>进行单元测试

时间:2017-06-12 20:32:12

标签: unit-testing spring-integration spring-integration-dsl

我在基于Spring Integration enrichHeader with randomUUID的代码中有以下定义:

@Bean
public Consumer<HeaderEnricherSpec> uriHeaderEnricher() {
    return new Consumer<HeaderEnricherSpec>() {
        private final String TIMESTAMP = "Timestamp";
        private final String MESSAGE_ID = "MessageId";

    @Override
        public void accept(HeaderEnricherSpec t) {
            t.headerFunction(MarklogicMessageHandler.URI, 
                    m -> "/event/" +
                         format(m.getHeaders().get(TIMESTAMP)) + "/" +
                         m.getHeaders().get(MESSAGE_ID) +
                         ".xml");
        }

        private String format(Object object) {
            if (!(object instanceof String)) {
                return "";
            }
            String string = (String) object;
            return string.substring(0, 10).replaceAll("-", "/");
        }

    };
}

我有点受阻,尽管这个代码的单元测试看起来像什么。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

因此,我们希望隔离测试中的类Consumer<HeaderEnricherSpec>,并断言该类与其他类的任何和所有交互,在本例中为HeaderEnricherSpec。我不确定你是否正在使用像Mockito这样的模拟框架,但我可以在Mockito中举例说明如何测试这个。事实证明有趣的是使用ArgumentCaptor捕获发送到headerFunction的lambda,然后你可以在测试中调用lambda以确保它按预期工作。

//This should invoke your bean method
@Autowired
private Consumer<HeaderEnricherSpec> consumer;

@Captor
private ArgumentCaptor<Function<WhateverTypeMIs, String>> lambdaCaptor; 

@Test
public void testAccept() {
    HeaderEnricherSpec spec = Mockito.mock(HeaderEnricherSpec.class);

    consumer.accept(spec);

    // Just showing you how to use the captor, don't forget to test URI
    verify(spec).headerFunction(any(), lambdaCaptor.capture());

    //This will be the lambda function you passed to `headerFunction`
    Function<WhateverTypeMIs, String> lambda = lambdaCaptor.getValue();

    //Now you need to call the lambda function just like you would if it were a separately testable function.
    String result = lambda.apply(m);
    //assertions on result string based on m input
}

如果您需要更多帮助或指导,请告诉我。

有关ArgumentCaptor的更多信息:docsStackOverflow Answer

Using ArgumentCaptor as field