Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Chris and Fildor are correct to try to mock the Logger.getLogger(). Unfortunately the way Log4J works makes that technically tricky.</p> <p>Here's the code I came up with (tested) based on your sample above.</p> <h3>ClassUnderTest.java</h3> <pre><code>import org.apache.log4j.Logger; public class ClassUnderTest { private static Logger logger = Logger.getLogger(ClassUnderTest.class); public void run() { logger.info("Hello."); } } </code></pre> <h3>MockLog4JTest.java</h3> <pre><code>import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import org.apache.log4j.Logger; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.Whitebox; @PrepareForTest(ClassUnderTest.class) public class MockLog4JTest { @Rule public PowerMockRule rule = new PowerMockRule(); @BeforeClass public static void oneTimeSetup() { System.setProperty("log4j.defaultInitOverride", Boolean.toString(true)); System.setProperty("log4j.ignoreTCL", Boolean.toString(true)); } @Test public void testLog() { ClassUnderTest classUnderTest = new ClassUnderTest(); Logger mockLogger = mock(Logger.class); Whitebox.setInternalState(ClassUnderTest.class, "logger", mockLogger); classUnderTest.run(); verify(mockLogger).info(eq("Hello.")); } } </code></pre> <p>I chose to go with using Whitebox to outright set the static field on the class under test to my <code>mockLogger</code> instance. After that, verification was pretty straightforward.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload