英文:
How to use Mockito verify to unit test @Slf4j logging in Spring Boot
问题
我有一个要求,需要将日志记录器作为模拟对象注入并验证日志方法的调用,而不创建自定义的附加程序。但是,我无法使用这种方法验证日志方法的调用。
@Mock
private Logger logger;
@Test
void testLoggedEvent() {  
    callTestMethod();
    verify(logger).error(anyString());
    verifyNoMoreInteractions(logger);
}
英文:
I have a requirement to inject the logger as a mock and verify the log method invocation without creating a custom appender. But I'm not able to verify that log method invocation with this approach.
@Mock
private Logger logger;
@Test
void testLoggedEvent() {  
    callTestMethod();
    verify(logger).error(anyString());
    verifyNoMoreInteractions(logger);
}
答案1
得分: 1
Sure, here is the translated code portion:
首先,不要忘记注入模拟对象并检查该方法被调用的次数。
应该看起来像这样:
@InjectMocks
private YourClassUnderTest classUnderTest;
@Test
void testLoggedEvent() {  
    // 调用被测试的方法
    classUnderTest.methodUnderTest();
    
    // 验证错误方法被调用一次
    verify(logger, times(1)).error(anyString());
    // 验证模拟日志记录器没有更多的交互
    verifyNoMoreInteractions(logger);
}
英文:
First of all, don't forget to inject the mocks and to check how many times the method has been called.
It should look like this:
@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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论