Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OuputCapture with multiple tests

I am using org.springframework.boot.test.OutputCapture to test an annotation that logs something.

It works brilliantly for a single test and when tests are run individually if there a multiple tests using output capture in a source file, but when multiple tests are run together only the first test run gets the captured output, the others get empty strings.

Is there any way to avoid this, I can't see any configuration possibilities?

This is a simplified test illustrating the problem import static org.hamcrest.Matchers.; import static org.junit.Assert.;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.boot.test.OutputCapture;

/** 
 * Simplest implementation that illustrates my problem using {@link OutputCapture}. 
 * <p>
 * If both tests are run, the second test run will not have any output captured so fails. 
 * If tests are run individually they both pass.
 * <p>
 * It is somehow related to 
 * 1) mocking with mockito which is not actually needed in this simplified implementation: without @InjectMocks no output is captured at all and both test fail. 
 * 2) if use System.out.println not log4j, both tests pass and output is captured without mocking as well. 
 */
@FixMethodOrder // done to illustrate error
public class OutputCaptureTests {

    @Rule 
    public OutputCapture outputCapture = new OutputCapture();

    @InjectMocks 
    private InternalTestListener listener;// = new InternalTestListener();

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Test 
    public void test1() {

        listener.doIt( 1 );
        assertThat( outputCapture.toString() , containsString( "doIt "+1 ) );
    }

    @Test 
    public void test2() {

        listener.doIt( 2 );
        assertThat( outputCapture.toString() , containsString( "doIt "+2 ) );
    }

    static class InternalTestListener{

        private static final Logger LOGGER = LogManager.getLogger( InternalTestListener.class );

        public void doIt( int x ){

            LOGGER.info( "doIt "+x );
//            System.out.println( "doIt "+x );
        }
    }
}
like image 288
stephen newman Avatar asked Apr 24 '26 11:04

stephen newman


1 Answers

I had the same problem and I resolved it like following:

Specifically was missing follow="true" to be added in the Console appender:

<Appenders>
<Console name="LogToConsole" target="SYSTEM_OUT" follow="true">
  ...
</Console>

In my case, as @Andy Wilkinson mentioned, was a configuration problem.

like image 197
Iker Aguayo Avatar answered Apr 27 '26 15:04

Iker Aguayo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!