本文介绍了使用log4j2和mockito声明日志消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently started used log4j2 and i am trying to test my log messages in my unit test. This was pretty straightforward with the log4j1x api, but now with log4j2 its not working. I am using JUnit 4 and Mockito. My idea is to create a mock appender and then capture the Log event from the append method and verify the message.

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

在我的@Before方法中,我有以下内容

In my @Before method i have the following

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方法。
有人对此有什么想法吗?谢谢

I am getting a failure saying the append method is never invoked.Anybody has any ideas on this? Thanks

推荐答案

mockAppender只是一个模拟对象。如果你没有在@Before方法中跟踪行,那么没什么可行的。

mockAppender is just a mock object. Nothing to work if you haven't following lines in your @Before method.

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

就我而言,它对我有用。

In my case, it works for me.

这篇关于使用log4j2和mockito声明日志消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:28