使用Lombok进行JUnit测试Log4j2日志记录

时间:2019-06-13 21:04:40

标签: java junit mockito log4j2 powermock

我有一个用lombok注释的Java类,如下所示:

@Log4j2
public class Foo {
  private boolean logStr = true;
  public void doStuff(String str) {
      if (logStr) {
          log.info(str);
      } else {
          log.info("some other string");
      }
  }
}

我正在尝试编写一个junit测试用例来测试doStuff方法。这是我的junit:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class, LogManager.class})
public class FooTest {
  private Foo foo;

  @BeforeClass
  public static void init()
  {
      System.setProperty("log4j.configurationFile","log4j2.properties");
  }

  @Before
  public void setUp() throws Exception {
      foo = new Foo();
  }

  @Test
  public void test()
  {
      PowerMockito.mockStatic(LogManager.class);
      Logger logger = mock(Logger.class);
      when(LogManager.getLogger(any(Class.class))).thenReturn(logger);
      foo.log("test");
      verify(logger).info("test");
  }
}

这是我的gradle导入:

compile "org.apache.logging.log4j:log4j-core:2.11.2"
compile "org.apache.logging.log4j:log4j-api:2.11.2"
testCompile 'org.powermock:powermock-api-mockito2:2.0.2'
testCompile 'org.powermock:powermock-module-junit4:2.0.2'
testCompile 'org.mockito:mockito-core:2.28.2'

但是每次我运行测试用例时,我都会得到:

Wanted but not invoked:
logger.info("test");
-> at org.Foo.test(FooTest.java:23)
Actually, there were zero interactions with this mock.

我在做什么错?有没有更简单的方法可以做到这一点,也许不需要PowerMock的解决方案?

0 个答案:

没有答案