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


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

public void setUp() {
Logger logger = Logger.getLogger(ConfigBasedActionLookupService.class);

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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s