使用mockito在java服务中模拟静态记录器的策略是什么

时间:2013-10-17 15:13:22

标签: logging junit mockito jmockit

我看到记录器已经在Powermock或某种被覆盖的构造函数的帮助下被嘲笑,后者需要记录器。

在整个代码中使用记录器,这不是他们使用mockito的简单方法吗?某种方式忽略调用或模拟它 - 我不想验证任何消息,只是想避免空指针异常

我是嘲笑框架的新手,所以我想知道使用Jmockit而不是混合和匹配两个库 - 到目前为止避免jomockit的唯一理由 - 太强大而且很容易被滥用!

1 个答案:

答案 0 :(得分:4)

在我认为在某个级别登录非常重要的情况下,我会使用日志验证。这就是我使用Mockito的方式:

公用事业类

public final class LoggingTestUtil {

    private LoggingTestUtil() {
    }

    public static void setupLoggingMock(Logger logger, Appender<ILoggingEvent> appender) {
        logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        when(appender.getName()).thenReturn("MOCK");
        logger.addAppender(appender);
    }

    public static void verifyLogAppended(Appender<ILoggingEvent> appender, final String loggedString) {
        verify(appender).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
            @Override
            public boolean matches(final Object argument) {
                return ((LoggingEvent) argument).getMessage().contains(loggedString);
            }
        }));
    }

    public static void verifyLogAppendedAtLevel(Appender<ILoggingEvent> appender, final Level level) {
        verify(appender).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
            @Override
            public boolean matches(final Object argument) {
                return ((LoggingEvent) argument).getLevel().equals(level);
            }
        }));
    }

    public static void verifyLogAppendedAtLevel(Appender<ILoggingEvent> appender, final Level level, final String loggedString) {
        verify(appender).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
            @Override
            public boolean matches(final Object argument) {
                LoggingEvent event = (LoggingEvent) argument;
                return event.getLevel().equals(level) && event.getMessage().contains(loggedString);
            }
        }));
    }
}

在测试类中

private static Logger root;
@Mock
private static Appender<ILoggingEvent> mockAppender; // used to test that logging occurs

    @Test
    public final void testSomething(){
        LoggingTestUtil.setupLoggingMocks(root, mockAppender);
        underTest.doSomethingBad();
        LoggingTestUtil.verifyLogAppendedAtLevel(mockAppender, Level.ERROR, "bad thing");
    }