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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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