如何使用Mockito验证在Spring Boot中对@Slf4j日志进行单元测试



我需要在不创建自定义附加程序的情况下将日志记录器作为模拟注入并验证日志方法调用。但是我无法用这种方法验证日志方法调用。

@Mock
private Logger logger;
@Test
void testLoggedEvent() {  
callTestMethod();
verify(logger).error(anyString());
verifyNoMoreInteractions(logger);
}

首先,不要忘记注入模拟并检查该方法被调用了多少次。它应该看起来像这样:

@InjectMocks
private YourClassUnderTest classUnderTest;
@Test
void testLoggedEvent() {  
// Call the method under test
classUnderTest.methodUnderTest();
// Verify that the error method was called once
verify(logger, times(1)).error(anyString());
// Verify that there are no more interactions with the mock logger
verifyNoMoreInteractions(logger);
}