使用Mockito,TestNG和Log4j2声明日志消息

时间:2018-06-28 20:50:52

标签: java-8 mockito testng log4j2

我一直遵循asserting-log-messages-with-log4j2-and-mockito编写TestNG测试来测试Log4j2的日志记录。帖子中写的大部分内容似乎都可以使用。但是,当我运行测试时,我得到:

Wanted but not invoked:
appender.append(<Capturing argument>);
-> at LoggingTest.test(LoggingTest.java:105)

However, there were exactly 2 interactions with this mock:
appender.getName();
-> at org.apache.logging.log4j.core.config.AbstractConfiguration.addAppender(AbstractConfiguration.java:603)

appender.getName();
-> at org.apache.logging.log4j.core.config.AppenderControl.<init>(AppenderControl.java:51)

我的TestNGclass是:

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.mockito.ArgumentCaptor;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class LoggingTest {

    private Appender appender;

    private ArgumentCaptor<LogEvent> captor;

    @BeforeMethod
    public void setUp() {
        appender = mock(Appender.class);
        captor = ArgumentCaptor.forClass(LogEvent.class);

        reset(appender);
        when(appender.getName()).thenReturn("Appender");
        when(appender.isStarted()).thenReturn(true);
        when(appender.isStopped()).thenReturn(false);

        LoggerContext context = (LoggerContext)LogManager.getContext();
        Configuration config = context.getConfiguration();
        config.addAppender(appender);
        LoggerConfig rootConfig = config.getRootLogger();
        rootConfig.setLevel(Level.INFO);
        rootConfig.addAppender(appender, Level.INFO, null);
        context.updateLoggers();
    }

    @Test
    public void test() {        
        LogManager.getLogger().info("testing");
        verify(appender).append(captor.capture());
        LogEvent logEvent = captor.getValue();
        assertThat(logEvent.getMessage()).isEqualTo("test");
    }
}

我已经看了一段时间了,却找不到我的错误。有人可以指出我正确的方向吗?

0 个答案:

没有答案