6

我看到记录器已在 Powermock 或某种需要记录器的重写构造函数的帮助下被模拟。

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

我是模拟框架的新手,所以我想使用 Jmockit 而不是混合和匹配两个库 - 到目前为止避免使用 jomockit 的唯一原因 - 它太强大了,很容易被滥用!

4

1 回答 1

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");
    }
于 2013-10-17T15:58:20.230 回答