asserting log messages with log4j2 and mockito

你。 提交于 2019-12-06 10:00:06

问题


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;

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

In my test method

logger.error("test");
verify(mockAppender, times(1)).append(logEvent.capture());

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


回答1:


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.




回答2:


(Not a real answer, but too long and too hard to read for a comment.)

For a start it seems a bit odd to assert on log messages, but I'm sure you have your reasons.

Your approach doesn't look wrong to me. Not 100% sure about the lifecycle of the logger context itself though, worst case scenario would be that everything is newed up for every class under test. In that case your appender wouldn't make it into production code. Maybe simplify a bit (no captor) and debug your test (you should be able to find the new appender somewhere).

Alternatively think about how you provision the logger to the components. Might be much easier to mock out that dependency.



来源:https://stackoverflow.com/questions/29356990/asserting-log-messages-with-log4j2-and-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!