如何测试只打印消息的方法

时间:2014-02-02 16:05:29

标签: java unit-testing

我有在游戏类中打印获胜者的方法:

public void getWinner(String winner){

   System.out.println("WINNER IS " + winner);

}

到目前为止,我如何测试此方法:

Game gm = new Game(); // it is declared in @before

@test

public void test(){

  ByteArrayOutputStream outContent = new ByteArrayOutputSystea();

  System.setOut(new PrintStream(outContent));

  gm.getWinner(Bob);

  assertEquals("WINNER IS Bob",outContent.toString());

}

我有一条说

的错误消息
org.unit.ComparisonFailuter expected:<WINNER IS Bob[]> but was: <WINNER IS Bob[
]>

那么请你给我一个关于如何测试getWinner方法的提示

4 个答案:

答案 0 :(得分:1)

omg不要这样做!您不必测试println方法。来自sun和oracle的人已经做到了 - 你可以肯定它有效。所有你需要测试的是你将正确的字符串传递给该方法。所以重构你的代码并创建一个返回所需字符串的函数,并通过简单的字符串比较来测试该方法

答案 1 :(得分:0)

来自documentation

public void println(String x)

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().

因此,当您在方法中打印该行时,其后面有一个行分隔符defined,如下所示:

The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

因此,您可以将硬编码行分隔符添加到预期输出中,也可以使用以下代码获取当前系统的分隔符并附加。:

System.getProperty("line.separator");

答案 2 :(得分:0)

模仿者的做法:

@Test
public void testGetWinner()
    {
    // setup: sut
    Game game = new Game();
    PrintStream mockPrintStream = EasyMock.createMock(PrintStream.class);
    System.setOut(mockPrintStream);

    // setup: data
    String theWinnerIs = "Bob";

    // setup: expectations
    System.out.println("WINNER IS " + theWinnerIs);

    // exercise
    EasyMock.replay(mockPrintStream);
    game.getWinner(theWinnerIs);

    // verify
    EasyMock.verify(mockPrintStream);
    }

亲:你不需要关心System.out.println()做什么,事实上如果实施改变你的测试仍然会通过。

答案 3 :(得分:-2)

当您使用==时,我认为您尝试与.equals()的字符串进行比较。字符串存储在一个常量池中,但是在这种情况下,你从其他地方读取一个字符串,这不一定会进入常量池。

尝试

assertTrue(outContent.toString().equals("WINNER IS Bob"));

或您的测试库所称的任何内容。

查找String中的字符而不是字符串的内存地址(“ref”)。