2014-09-26 91 views
1

我有一些方法,诸如Add(int n)AddAt(int n, int index)一个简单的数组类等JUnit进行测试System.err.print()

的addAt方法调用从超类

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

另一种方法,检查插入的索引是否出界,如果是这样,则超类方法向控制台输出错误消息。

我应该如何测试,如果邮件打印?我正在使用JUnit4.12-beta

+0

可能重复[?我们是否应该单元测试的控制台输出(http://stackoverflow.com/questions/15175175/should-we-单元测试控制台输出) – Joe 2014-09-26 12:22:37

+0

是的我已经看到了,但答案是取决于您的代码 – 2014-09-26 14:28:25

回答

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

在这里你的意思是outContent变量应该流的东西打印在控制台上?我已经尝试过,但outContent始终为空 – 2014-09-26 14:24:22

+0

@AmirHM:对,修复了我的答案。使用'setErr'而不是'setOut',因为'err'和'out'是不同的流。现在这应该工作。 – Simulant 2014-09-26 14:50:08

+0

感谢它的工作 – 2014-09-26 15:52:51