春豆豆仍然什么也没做,尽管做了答案设置



我正在尝试在其 void 方法上存根注入的依赖项:

@Autowired
private FeedbackService service;
@MockBean
private MailSender sender;
@Test
public void testMonitor() {
// mocking MailSender#sendMessage
Mockito.doAnswer(invocation -> {
log.info("SUBJECT: {}", invocation.getArgument(0, String.class));
log.info("CONTENT: {}", invocation.getArgument(1, String.class));
for (String dest : (String[]) invocation.getArgument(2)) {
log.info("DEST: {}", dest);
}
return null;    // Void anyway
}).when(sender).sendMessage(anyString(), anyString(), any(String[].class)); //FIXME still doNothing
// invoking the service which calls MailSender#sendMessage
service.monitor();
}

但日志记录和调试显示运行时不会发生拦截。 请问有人知道我做错了什么吗?

字符串数组的铸造似乎比我想象的要棘手。这可以用作拦截器:

.sendMessage(anyString(), anyString(), any());

但是第三个参数作为字符串而不是字符串数组到达。 注意:第三个参数是一个变量,但 #anyVararg 也不起作用。

好的,我终于发现,即使编译器允许将 varargs 视为数组,调用参数仍将参数视为单独的实体。

@Test
public void testMonitor() {
// mocking MailSender#sendMessage
Mockito.doAnswer(invocation -> {
log.info("SUBJECT: {}", invocation.getArgument(0, String.class));
log.info("CONTENT: {}", invocation.getArgument(1, String.class));
for (int i = 2; i < invocation.getArguments().length; i++) {
log.info("DEST: {}", (String) invocation.getArgument(i));
}
return null;    // Void
}).when(sender)
.sendMessage(anyString(), anyString(), (String[]) any());
// invoking the service, depending on the above stub
service.monitor();
}

相关内容

最新更新