3

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

Simulant
  • 19,190
  • 8
  • 63
  • 98
Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
  • possible duplicate of [Should we unit test console outputs?](http://stackoverflow.com/questions/15175175/should-we-unit-test-console-outputs) – Joe Sep 26 '14 at 12:22
  • yes I have seen that , but the answer is it depends on your code – Amir-Mousavi Sep 26 '14 at 14:28

3 Answers3

7
@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());
}
Simulant
  • 19,190
  • 8
  • 63
  • 98
  • here you mean outContent variable should stream what ever is printed on console ? I have tried it but outContent is always null – Amir-Mousavi Sep 26 '14 at 14:24
  • @AmirHM: right, fixed my answer. Use `setErr` instead of `setOut` because `err` and `out` are different streams. Now this should work. – Simulant Sep 26 '14 at 14:50
0

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

Timo
  • 2,212
  • 2
  • 25
  • 46
0

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?

phtrivier
  • 13,047
  • 6
  • 48
  • 79