问题
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