【发布时间】:2026-02-15 03:40:01
【问题描述】:
我正在尝试测试编写为 lambda 的 RabbitTemplate#convertAndSend 方法,如下所示:
// other stuff omitted for brevity
rabbitTemplate.convertAndSend(myQueue, jsonString, message -> {
message.getMessageProperties().setPriority(priority);
return message;
});
// other stuff omitted for brevity
我正在尝试做的测试用例是使用ArgumentCaptor 以验证是否使用正确的参数调用了该方法。
@Test
public void givenMyNotification_whenElementIsSent_thenSetPriorityAndSendValidParameters() {
final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
final int expectedPriority = 5;
final Notification expected = TestUtils.getNotification();
testClass.handleNotification(expected);
verify(rabbitTemplate).convertAndSend(captor.capture(), captor.capture(),
ArgumentMatchers.eq(MessagePostProcessor.class));
// assertThat...
));
}
在验证步骤测试失败,因为参数不同。
Wanted:
<Capturing argument>,
<Capturing argument>,
interface org.springframework.amqp.core.MessagePostProcessor
Actual invocation:
"myQueue",
"myJson",
com.example.notification.service.NotificationService$$Lambda$5/73698537@5bda80bf
我尝试了其他几个来自 mockito 和 hamcrest 的 Matcher,但都无济于事。
所以,我的问题是:
如何测试这种东西?
这是一个好的做法还是有其他/更好的方法来测试兔子模板发送?
【问题讨论】:
标签: java spring-boot junit rabbitmq mockito