我最近开始使用log4j2,并且尝试在单元测试中测试日志消息。使用log4j1x api非常简单,但是现在使用log4j2则无法正常工作。我正在使用JUnit 4和Mockito。我的想法是创建一个模拟追加器,然后从append方法捕获Log事件并验证消息。

@Mock
Appender mockAppender;
@Captor
private ArgumentCaptor<LogEvent> logEvent;

在我的@Before方法中,我有以下内容
LoggerContext ctx = (LoggerContext)LogManager.getContext();
Configuration config = ctx.getConfiguration();
ctx.getConfiguration().addAppender(mockAppender);
LoggerConfig rootConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
rootConfig.setLevel(Level.DEBUG);
rootConfig.addAppender(mockAppender, Level.DEBUG, null);
ctx.updateLoggers();

在我的测试方法中
logger.error("test");
verify(mockAppender, times(1)).append(logEvent.capture());

我收到一个失败的消息,说从未调用过append方法。
有人对此有任何想法吗?谢谢

最佳答案

mockAppender只是一个模拟对象。如果您未在@Before方法中遵循以下行,则无济于事。

Mockito.reset(mockAppender);
Mockito.when(mockAppender.getName()).thenReturn("MockAppender");
Mockito.when(mockAppender.isStarted()).thenReturn(true);
Mockito.when(mockAppender.isStopped()).thenReturn(false);

就我而言,它对我有用。

09-27 06:06