Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asserting log messages with log4j2 and mockito

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

like image 832
Gowtham Avatar asked Sep 11 '25 22:09

Gowtham


1 Answers

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.

like image 83
hiroyukik Avatar answered Sep 14 '25 11:09

hiroyukik