Last active
December 29, 2015 08:39
-
-
Save mariuszs/7644502 to your computer and use it in GitHub Desktop.
Testing Logback Logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Solution without PowerMock | |
-- | |
import ch.qos.logback.classic.*; | |
import ch.qos.logback.classic.spi.LoggingEvent; | |
import ch.qos.logback.core.Appender; | |
import org.junit.*; | |
import org.junit.runner.RunWith; | |
import org.mockito.*; | |
import org.mockito.runners.MockitoJUnitRunner; | |
import org.slf4j.LoggerFactory; | |
import static org.mockito.Matchers.argThat; | |
import static org.mockito.Mockito.*; | |
@RunWith(MockitoJUnitRunner.class) | |
public class XTest { | |
@Mock | |
Appender mockAppender; | |
X x = new X(); | |
@Before | |
public void setUp() throws Exception { | |
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); | |
root.addAppender(mockAppender); | |
} | |
@Test | |
public void whenFirstCaseErrorLogged() throws Exception { | |
x.execute(true); | |
thenLogged(Level.ERROR, "rumpampam"); | |
} | |
@Test | |
public void whenSecondCaseErrorLogged() throws Exception { | |
x.execute(false); | |
thenLogged(Level.ERROR, "latida"); | |
} | |
private void thenLogged(Level level, String message) { | |
verify(mockAppender).doAppend(argThat(hasLogged(level, message))); | |
} | |
private ArgumentMatcher hasLogged(final Level level, final String message) { | |
return new ArgumentMatcher() { | |
@Override | |
public boolean matches(final Object argument) { | |
LoggingEvent loggingEvent = (LoggingEvent) argument; | |
return loggingEvent.getLevel().equals(level) && | |
loggingEvent.getFormattedMessage().contains(message); | |
} | |
}; | |
} | |
} | |
Solution based on excellent post [Functional testing : Asserting that a line was logged by Logback](http://jsoftbiz.wordpress.com/2011/11/29/unit-testing-asserting-that-a-line-was-logged-by-logback/) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment