Skip to content

Commit

Permalink
♻️ Refactor test to use a logging appender instead of capturing stand…
Browse files Browse the repository at this point in the history
…ard out

Signed-off-by: Marcus Fihlon <[email protected]>
  • Loading branch information
McPringle committed Nov 4, 2024
1 parent 77c5563 commit d664105
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/test/java/swiss/fihlon/apus/event/TrackTest.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package swiss.fihlon.apus.event;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
import swiss.fihlon.apus.MemoryAppender;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.stream.Stream;
Expand Down Expand Up @@ -56,22 +59,21 @@ void customTrack() {

@Test
void customTrackLogException() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final var standardOut = System.out;
final var outputStreamCaptor = new ByteArrayOutputStream();
final MemoryAppender memoryAppender = new MemoryAppender();
memoryAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory());
@SuppressWarnings("LoggerInitializedWithForeignClass") final Logger logger = (Logger) LoggerFactory.getLogger(Track.class);
logger.addAppender(memoryAppender);

try {
System.setOut(new PrintStream(outputStreamCaptor));
memoryAppender.start();
final Method defaultTrackMethod = Track.class.getDeclaredMethod("defaultTrack", String.class);
defaultTrackMethod.setAccessible(true);
final var track = defaultTrackMethod.invoke(String.class, "non-existing-file.svg");
assertEquals(Track.NONE, track);
memoryAppender.stop();

final Method defaultTrackMethod = Track.class.getDeclaredMethod("defaultTrack", String.class);
defaultTrackMethod.setAccessible(true);
final var track = defaultTrackMethod.invoke(String.class, "non-existing-file.svg");
assertEquals(Track.NONE, track);

final String out = outputStreamCaptor.toString();
assertTrue(out.contains("Unable to load default track icon 'non-existing-file.svg':"));
} finally {
System.setOut(standardOut);
}
final int errorCount = memoryAppender.searchFormattedMessages(
"Unable to load default track icon 'non-existing-file.svg':", Level.ERROR).size();
assertEquals(1, errorCount);
}

}

0 comments on commit d664105

Please sign in to comment.