简体   繁体   中英

JUnit testing System.err.print()

I have a simple array class with some methods such as Add(int n) , AddAt(int n, int index) , etc.

the addAt method calls another method from super class

public void addAt(int n, int index) {
    if (checkIndex(index, size + 1)){
        ...
    }
}

that checks if the inserted index is not out-bounded, if so the super class method prints an error message to console.

how should I test that if the message is printed? I am using JUnit4.12-beta

@Test
public void testPrint() {
    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    //redirect the System-output (normaly the console) to a variable
    System.setErr(new PrintStream(outContent));

    //call your method here

    //check if your error message is in the output variable
    assertEquals("your output", outContent.toString());
}

You could also use a mocking framework to mock the target object and check whether or not the target method has been called.

See for instance http://eclipsesource.com/blogs/2011/10/13/effective-mockito-part-3/

This might be a bit of an investment if you do not have such a framework in place already...

Can't you make your life simpler by raising exceptions rather than printing messages ?

In which case you can use 'expected' exceptions like here : How do you assert that a certain exception is thrown in JUnit 4 tests?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM