Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
unit test Log calls in Java with PowerMock
/**
* call logs
*/
public class LogCaller {
private static Logger LOG = LoggerFactory.getLogger(LogCaller.class);
public void testLogging() {
LOG.info("Hello World");
}
}
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
/**
* Test log is called
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class LogCallerTest {
private static Logger mockLOG;
@InjectMocks
LogCaller underTest;
@BeforeClass
public static void setup() {
mockStatic(LoggerFactory.class);
mockLOG = mock(Logger.class);
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
}
@Test
public void testLogging() {
underTest.testLogging();
verify(mockLOG).info("Hello World");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment