Created
December 12, 2016 09:55
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
// Fully working test at: https://github.com/njaiswal/logLineTester/blob/master/src/test/java/com/nj/Utils/UtilsTest.java | |
@Test | |
public void testUtilsLog() throws InterruptedException { | |
Logger utilsLogger = (Logger) LoggerFactory.getLogger("com.nj.utils"); | |
final Appender mockAppender = mock(Appender.class); | |
when(mockAppender.getName()).thenReturn("MOCK"); | |
utilsLogger.addAppender(mockAppender); | |
final List<String> capturedLogs = Collections.synchronizedList(new ArrayList<>()); | |
final CountDownLatch latch = new CountDownLatch(3); | |
//Capture logs | |
doAnswer((invocation) -> { | |
LoggingEvent loggingEvent = invocation.getArgumentAt(0, LoggingEvent.class); | |
capturedLogs.add(loggingEvent.getFormattedMessage()); | |
latch.countDown(); | |
return null; | |
}).when(mockAppender).doAppend(any()); | |
//Call method which will do logging to be tested | |
Application.main(null); | |
//Wait 5 seconds for latch to be true. That means 3 log lines were logged | |
assertThat(latch.await(5L, TimeUnit.SECONDS), is(true)); | |
//Now assert the captured logs | |
assertThat(capturedLogs, hasItem(containsString("One"))); | |
assertThat(capturedLogs, hasItem(containsString("Two"))); | |
assertThat(capturedLogs, hasItem(containsString("Three"))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment