Amir-Mousavi
Amir-Mousavi

Reputation: 4563

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

Upvotes: 3

Views: 3702

Answers (3)

phtrivier
phtrivier

Reputation: 13361

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?

Upvotes: 0

Simulant
Simulant

Reputation: 20102

@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());
}

Upvotes: 7

Timo
Timo

Reputation: 2242

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...

Upvotes: 0

Related Questions