怎么使用Mockito的verify来单元测试Spring Boot中的@Slf4j日志记录。

huangapple go评论59阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2023年4月4日 05:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定