mardi 3 novembre 2015

Unit testing logs using streams working just for the first test

I have a JUnit test class, which uses Mockito, in which I need to test if something is being logged correctly. It basically looks something like:

public class MyTest {

    private final PrintStream outDefault = System.out;
    private final PrintStream errDefault = System.err;

    private final ByteArrayOutputStream outContent = new ByteArrayOutputSteam();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();

    @Before
    public void setUp() {
        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));  
    }

    @After
    public void takingDown() {
        System.setOut(outDefault);
        System.setErr(errDefault);
    }

    @Test
    public Test1_Condition_Expected() {
        assertTrue(errContent.toString().toLowerCase().contains("...")):
    }

    ...

    @Test
    public TestN_Condition_Expected() {
        assertTrue(errContent.toString().toLowerCase().contains("...")):
    }
}

I have also tried to do a flush and close of the streams in the @After, but it does not seem to work neither:

@After
public void takingDown() {
    try {
        outContent.flush();
        errContent.flush();
        outContent.close();
        errContent.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.setOut(outDefault);
    System.setErr(errDefault);
}

When I run the whole class, the first tests passes but the rest don't. If I run the tests one by one then all of them passes.

I have debugged the code and everything seems to work properly, but for tests other than the first one the streams are not getting the logs, so obviously they fail.

Aucun commentaire:

Enregistrer un commentaire