How to test method that only print out message

I have method that print winner in the class Game:

public void getWinner(String winner){

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


How can I test this method so far I have:

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


public void test(){

  ByteArrayOutputStream outContent = new ByteArrayOutputSystea();

  System.setOut(new PrintStream(outContent));


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


I have an error message that say

org.unit.ComparisonFailuter expected:<WINNER IS Bob[]> but was: <WINNER IS Bob[

Well could you please give me a tip on how to test getWinner method


omg don't do it! you don't have to test the println method. guys from sun and oracle have already done that - you can be sure it works. all you have to test is that you pass the right string to to that method. so refactor your code and create a function that return the desired string and test only that method by simple string comparison

From the 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().

So when you print the line in the method, there's a line separator after it which is defined as so:

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

So you can either add a hardcoded line separator to your expected output, or you could use the following code to get the separator for the current system and append that.:


A mockist approach:

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

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

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

    // exercise

    // verify

Pro: You don't need to care what System.out.println() does, in fact if the implementation changes your test will still pass.

I think you try to compare to strings with == when you should use .equals(). The strings are stored i a constant pool, but in this case you read a string from somewhere else, which not nescessarily goes into the constant pool.


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

or whatever your testing library calls it.

which looks for the characters in the String instead of the memory address ("ref") of the String.

Need Your Help

Recording audio output from application

c++ winapi audio video record

I'm currently building a project on C++ using Visual Studio on Windows 8. This application captures video from camera and triggers some virtual animations in real-time, with some sounds being played