Mockito似乎无法模拟slf4j接口



我正试图为slf4jLogger接口制作一个包装器并对其进行测试,但我一直收到以下错误。

TestDebugLog FAILED
Wanted but not invoked:
logger.debug("some message", "arg1", "arg2");
-> at com.common.TrebuchetLoggerTest.TestDebugLog(TrebuchetLoggerTest.java:37)
However, there was exactly 1 interaction with this mock:
logger.debug("some message", "arg1", "arg2");
-> at com.common.TrebuchetLogger.debug(TrebuchetLogger.java:19)
at com.common.TrebuchetLoggerTest.TestDebugLog(TrebuchetLoggerTest.java:37)
1 test completed, 1 failed

我的测试看起来像

@RunWith(MockitoJUnitRunner.class)
public class TrebuchetLoggerTest {
TrebuchetLogger trebuchetLogger;
@Mock TrebuchetClient trebuchetClient;
@Mock Logger logger;
@Before
public void setup() {
trebuchetClient = mock(TrebuchetClient.class);
when(trebuchetClient.launch(any(String.class))).thenReturn(true);
logger = mock(Logger.class);
trebuchetLogger = new TrebuchetLogger(trebuchetClient, logger);
}
@Test
public void TestDebugLog() {
trebuchetLogger.debug("debug-suffix", "some message", "arg1", "arg2");
verify(logger).debug("some message", "arg1", "arg2");
}
}

我的代码是:

package com.common;
import org.slf4j.Logger;
import lombok.NonNull;
import com.trebuchet.client.TrebuchetClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import javax.inject.Inject;
import org.slf4j.LoggerFactory;
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class TrebuchetLogger {
@NonNull private TrebuchetClient trebuchetClient;
@NonNull private Logger log;
public void debug(String trebuchetSuffix, String format, Object... arguments) {
if (trebuchetClient.launch(trebuchetSuffix)) {
log.debug(format, arguments);
}
}
public void info(String trebuchetSuffix, String format, Object... arguments) {
if (trebuchetClient.launch(trebuchetSuffix)) {
log.info(format, arguments);
}
}
public void warn(String trebuchetSuffix, String format, Object... arguments) {
if (trebuchetClient.launch(trebuchetSuffix)) {
log.warn(format, arguments);
}
}
public void error(String trebuchetSuffix, String format, Object... arguments) {
if (trebuchetClient.launch(trebuchetSuffix)) {
log.error(format, arguments);
}
}
}

为什么我的mockito mock失败了,错误消息中的结果似乎完全相同?

您正在SUT中调用不同的重载并进行验证。

// SUT
log.debug(format, arguments);
// Test
verify(logger).debug("some message", "arg1", "arg2");

对应过载:

  • 调试​(字符串格式,对象…参数(
  • 调试​(字符串格式,对象arg1,对象arg2(

如果在有一个格式和两个参数时需要调用varargs重载,则需要将参数作为数组传递。

最新更新