Spring Boot中如何使用Mockito验证单元测试@Slf4j登录

问题描述 投票:0回答:1

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

@Mock
private Logger logger;

@Test
void testLoggedEvent() {  
    callTestMethod();
    verify(logger).error(anyString());
    verifyNoMoreInteractions(logger);
}
java mockito junit5 powermock
1个回答
0
投票

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

@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);
}
© www.soinside.com 2019 - 2024. All rights reserved.