如何对消费者进行单元测试<HeaderSpec>

How to unit test a Consumer<HeaderSpec>

基于我的代码中有以下定义:

@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("-", "/");
        }

    };
}

虽然我对这段代码的单元测试是什么样的感到有点困惑。有什么建议吗?

所以我们想要隔离 class 被测试 Consumer<HeaderEnricherSpec> 并断言 class 与其他 class 的任何和所有交互,在这种情况下 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 的更多信息:docs, Whosebug Answer

Using ArgumentCaptor as field