简体   繁体   English

Powermock:模拟静态最终记录器

[英]Powermock: Mocking static final logger

I am trying to write tests that check whether certain lines have been logged.我正在尝试编写测试来检查是否已记录某些行。 I googled for a while but I cannot figure out why LOG is not replaced.我用谷歌搜索了一段时间,但我不明白为什么LOG没有被替换。

Class to test:要测试的类:

public class Example {
    private static final Logger LOG = LoggerFactory.getLogger(Example.class);

    public void foo(...)
    {
       if(...)
         LOG.warn("Warning");
       //...
    }
}

Test:测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyTest
{
    @Mock
    Logger logger;

    @InjectMocks
    private final Example example = new Example();

    @Test
    public void test1() {
        PowerMockito.mockStatic(LoggerFactory.class);
        logger = PowerMockito.mock(Logger.class);
        PowerMockito.when(LoggerFactory.getLogger(Example.class)).thenReturn(logger);

        example.foo(...);

        Mockito.verify(logger).warn("Warning");
    }
}

SLF4J is used and PowerMock 1.7.1.使用 SLF4J 和 PowerMock 1.7.1。

PS: Replacing private static final Logger LOG is no option in this project. PS:替换private static final Logger LOG在这个项目中是没有选项的。

You are creating your subject too early.您过早地创建主题。 You arrange the mock well after the subject has already been created.在创建主题后,您可以很好地安排模拟。

create the subject after arranging the static mock安排静态模拟后创建主题

@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyTest {

    @Test
    public void test1() {
        //Arrange
        Logger logger = PowerMockito.mock(Logger.class);

        PowerMockito.mockStatic(LoggerFactory.class);           
        PowerMockito.when(LoggerFactory.getLogger(Example.class)).thenReturn(logger);

        Example example = new Example();

        //Act
        example.foo(..);

        //Assert
        Mockito.verify(logger).warn("Warning");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM