Mocking static Logger without PowerMock

Suppose you have a class that uses a static Logger to log some error, and you would like to unit test including the message logged. One approach is to use PowerMock because the Logger is usually declared static in your class. However for logging, you don’t need to add PowerMock to your dependency if you don’t already use it. Here’s an example:

public class MyClass {
private static final Logger LOGGER = Logger.getLogger(MyClass.class);
public void myMethod() {
try {
// ...
}
catch ( ... ) {
LOGGER.error("my error message");
}
}
}

 

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private Appender logAppender;
@Captor
private ArgumentCaptor loggingEventArgumentCaptor = ArgumentCaptor.forClass(LoggingEvent.class);</code>

@Before
public void setUp() {
Logger logger = Logger.getLogger(ConfigBasedActionLookupService.class);
logger.addAppender(logAppender);
logger.setLevel(Level.INFO);
}

@Test
public void myMethod_invalidConditions_shouldLogError() {
verify(logAppender, times(1)).doAppend(loggingEventArgumentCaptor.capture());
LoggingEvent actualLoggingEvent = loggingEventArgumentCaptor.getValue();
assertThat(actualLoggingEvent, is(notNullValue()));
assertThat(actualLoggingEvent.getRenderedMessage(), containsString("my error message"));
}

Leave a comment