-3
public void declareWinner()
        {
         compare and declare winner 
            if(getLive_player1()==0 && getLive_player2()>0)
            {
                System.out.println("Player 2 wins with "+getLive_player2()+" cells alive.");
            }
            else if(getLive_player2()==0 && getLive_player1()>0)
            {
                System.out.println("Player 1 wins with "+getLive_player1()+" cells alive.");
            }
            else
            {
                System.out.println("There is a tie.");
            }
        }
nabinca
  • 2,002
  • 1
  • 18
  • 29
  • 4
    possible duplicate of [JUnit test for System.out.println()](http://stackoverflow.com/questions/1119385/junit-test-for-system-out-println) – kryger Sep 24 '15 at 19:13
  • don't see how this is unclear? – vikingsteve Sep 24 '15 at 20:35
  • Himanshu, suggest you separate the logic that returns a particular string into a method returning `String` - and then unit test that (much easier than messing with streams) – vikingsteve Sep 24 '15 at 20:36

1 Answers1

1

Well, it's clear that you have a handful of different branches in your code, so you'll want to implement unit tests where you can hit your if and else if statements:

  • player1 = 0 and player2 > 0
  • player1 = 0 and player1 > 0

As well as a test where you hit your else statement:

  • Clearly multiple options, but player1 > 0 and player2 > 0 will suffice to reach that branch.

So that's at least three different @Test methods.

I'm assuming your concern is determining how to capture the System.out calls. You can change the out stream to one which points to something that can be captured programmatically. That is achieved with System.setOut():

@Test
public void testSomething() {
  ByteArrayOutputStream myOut = new ByteArrayOutputStream();
  System.setOut(new PrintStream(myOut));
  // do your setup and then execute declareWinner()...
  String methodOutput = myOut.toString();
  // Use Assert.assertEquals(...) to check methodOutput against expected value...
}

By the way

Based on what I can see, how do you know that two scores > 0 end in a tie? Seems like the else statement hasn't really closed out all of the options. But then again, I'm not sure what you're underlying code is doing...

Keith
  • 3,079
  • 2
  • 17
  • 26