OuputCapture有多个测试

时间:2016-05-23 00:12:14

标签: testing spring-boot

我正在使用org.springframework.boot.test.OutputCapture来测试记录某些内容的注释。

对于单个测试,如果在源文件中使用输出捕获进行多个测试,则单独运行测试,但是当多个测试一起运行时,只有第一个测试运行获取捕获的输出,其他测试为空字符串。

有什么方法可以避免这种情况,我看不到任何配置可能性吗?

这是一个说明问题的简化测试     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 );
        }
    }
}

0 个答案:

没有答案