Spring 尽管有 doAnswer 设置,mockito bean 仍然什么都不做
Spring mockito bean still does nothing, despite doAnswer setting
我正在尝试将注入的依赖存入其 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 也不起作用。
好吧,我终于想通了,即使编译器允许将可变参数视为数组,调用参数仍会将参数视为单独的实体。
@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();
}
我正在尝试将注入的依赖存入其 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 也不起作用。
好吧,我终于想通了,即使编译器允许将可变参数视为数组,调用参数仍会将参数视为单独的实体。
@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();
}