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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With