2015-03-16 8 views

risposta

11

È 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()); 
    ... 
} 
+4

Nota: se si utilizza logback classic + slf4j è necessario utilizzare 'ILoggingEvent' anziché' LoggingEvent'. Questo è quello che ha funzionato per me. – etech

+0

@Evgeniy Dorofeev Potresti mostrare come configurare logback-test.xml? – hipokito

+0

Suppongo che sia necessario cancellare gli eventi 'dopo ogni esecuzione del test. –

6

È 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(); 
    } 
} 
+0

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

2

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.

Problemi correlati