È possibile in qualche modo intercettare la registrazione (SLF4J + logback) e ottenere un InputStream
(o qualcos'altro che sia leggibile) tramite un caso di test JUnit ...?Come intercettare la registrazione SLF4J tramite un test JUnit?
risposta
È possibile creare un custom appender
public class TestAppender extends AppenderBase<LoggingEvent> {
static List<LoggingEvent> events = new ArrayList<>();
@Override
protected void append(LoggingEvent e) {
events.add(e);
}
}
e configurare logback-test.xml per usarlo. Ora siamo in grado di controllare la registrazione degli eventi dal nostro test:
@Test
public void test() {
...
Assert.assertEquals(1, TestAppender.events.size());
...
}
È possibile utilizzare slf4j-test dal http://projects.lidalia.org.uk/slf4j-test/. Sostituisce l'intera implementazione di logback slf4j con la propria implementazione di slf4j api per i test e fornisce una API per asserire contro eventi di registrazione.
esempio:
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<classpathDependencyExcludes>
<classpathDependencyExcludes>ch.qos.logback:logback-classic</classpathDependencyExcludes>
</classpathDependencyExcludes>
</configuration>
</plugin>
</plugins>
</build>
public class Slf4jUser {
private static final Logger logger = LoggerFactory.getLogger(Slf4jUser.class);
public void aMethodThatLogs() {
logger.info("Hello World!");
}
}
public class Slf4jUserTest {
Slf4jUser slf4jUser = new Slf4jUser();
TestLogger logger = TestLoggerFactory.getTestLogger(Slf4jUser.class);
@Test
public void aMethodThatLogsLogsAsExpected() {
slf4jUser.aMethodThatLogs();
assertThat(logger.getLoggingEvents(), is(asList(info("Hello World!"))));
}
@After
public void clearLoggers() {
TestLoggerFactory.clear();
}
}
Grazie per questa risposta alternativa! Sembra molto utile e probabilmente tenterò questo approccio anche in futuro! Sfortunatamente, ho già accettato l'altra risposta che è anche corretta. – carlspring
ho avuto problemi durante il test linea di tronchi come: LOGGER.error (messaggio, eccezione).
La soluzione descritta in http://projects.lidalia.org.uk/slf4j-test/ tenta di affermare anche l'eccezione e non è facile (e secondo me inutile) ricreare lo stacktrace.
ho risolto in questo modo:
import org.junit.Test;
import org.slf4j.Logger;
import uk.org.lidalia.slf4jext.LoggerFactory;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static uk.org.lidalia.slf4jext.Level.ERROR;
import static uk.org.lidalia.slf4jext.Level.INFO;
public class Slf4jLoggerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(Slf4jLoggerTest.class);
private void methodUnderTestInSomeClassInProductionCode() {
LOGGER.info("info message");
LOGGER.error("error message");
LOGGER.error("error message with exception", new RuntimeException("this part is not tested"));
}
private static final TestLogger TEST_LOGGER = TestLoggerFactory.getTestLogger(Slf4jLoggerTest.class);
@Test
public void testForMethod() throws Exception {
// when
methodUnderTestInSomeClassInProductionCode();
// then
assertThat(TEST_LOGGER.getLoggingEvents()).extracting("level", "message").contains(
tuple(INFO, "info message"),
tuple(ERROR, "error message"),
tuple(ERROR, "error message with exception")
);
}
}
Questo ha così il vantaggio di non avere dipendono Hamcrest matchers biblioteca.
Nota: se si utilizza logback classic + slf4j è necessario utilizzare 'ILoggingEvent' anziché' LoggingEvent'. Questo è quello che ha funzionato per me. – etech
@Evgeniy Dorofeev Potresti mostrare come configurare logback-test.xml? – hipokito
Suppongo che sia necessario cancellare gli eventi 'dopo ogni esecuzione del test. –