Skip to content

Instantly share code, notes, and snippets.

@javathought
Created May 11, 2017 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javathought/e925f3846a3b1d8ea4ece7609937f250 to your computer and use it in GitHub Desktop.
Save javathought/e925f3846a3b1d8ea4ece7609937f250 to your computer and use it in GitHub Desktop.
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");
}
}
@atilla8huno
Copy link

cheers

@Simonxyzjz
Copy link

good work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment