Created
December 22, 2016 08:03
-
-
Save m-x-k/7f185555fee48042408c910f661b9248 to your computer and use it in GitHub Desktop.
Junit assert log statements
This file contains hidden or 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
public class BaseTest { | |
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); | |
@Mock | |
protected Appender mockAppender; | |
@Captor | |
protected ArgumentCaptor<LoggingEvent> captorLoggingEvent; | |
@Before | |
public void setup() throws Exception { | |
MockitoAnnotations.initMocks(this); | |
logger.addAppender(mockAppender); | |
} | |
@After | |
public void teardown() { | |
logger.detachAppender(mockAppender); | |
} | |
protected void assertInLogMessages(Level level, String errorText, boolean checkStacktrace) { | |
if (isEmpty(errorText)) | |
fail("Error text should not be empty"); | |
verify(mockAppender, atLeastOnce()).doAppend(captorLoggingEvent.capture()); | |
boolean isFound = false; | |
LoggingEvent loggingEventMatched = null; | |
for (LoggingEvent loggingEvent : captorLoggingEvent.getAllValues()) { | |
if (level == loggingEvent.getLevel() && | |
loggingEvent.getMessage() != null && | |
loggingEvent.getMessage().contains(errorText)) { | |
isFound = true; | |
loggingEventMatched = loggingEvent; | |
} | |
} | |
// fail if error not found in logs | |
String assertFailureMessage = format("Not in logfile: Level='%s' Error='%s'", level, errorText); | |
assertTrue(assertFailureMessage, isFound); | |
// ensure logged event has stacktrace | |
if (checkStacktrace) | |
assertNotNull(loggingEventMatched.getThrowableProxy().getStackTraceElementProxyArray()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment