5

I know there are several question about void-method Unit-Testing, but my question is different.
I'm learning java, so my boss give me some tasks with different requirements on my tasks.

In my actual task, there is a requirement which says, the jUnit test must cover >60%. So I need to test a very simple method to reach this 60%. The method is the following:

public void updateGreen() {
    // delete this outprint if the Power Manager works
    System.out.println(onCommand + "-green");
    // p = Runtime.getRuntime().exec(command + "-green");
    // wait until the command is finished
    // p.waitFor();
}

Because of intern problems, I can't execute the command with the Runtime task. So there is only a System.out in this method.

I've multiple methods like that, so tests for this method will cover over 10% of my whole code.

Is it useful to test such a method? When yes, how?

3 Answers3

16

If there is a lot of such methods, the thing which you might want to test here is that updateScreen() uses the right string, "some-command-green" and that the System.out is being invoked. In order to do this you might want to extract System.out into an object field and mock it (i.e. with Mockito's spy()) to test the string that was provided to println.

I.e.

class MyClass{
     PrintStream out = System.out;

     public void updateGreen() { ... }
}

In test:

@Test
public void testUpdate(){
     MyClass myClass = new MyClass();
     myClass.out = Mockito.spy(new PrintStream(...));

     // mock a call with an expected input
     doNothing().when(myClass.out).println("expected command");

     myClass.updateGreen();

     // test that there was a call
     Mockito.verify(myClass.out, Mockito.times(1)).println("expected command");
}
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
0

You could return true if the method ran successfully and false otherwise. It would be easy to test for this.

You could also test the output of this method, as described here: Should we unit test console outputs?

But in my experience, it is much better to have methods return an optimistic or pessimistic value (true/false, 1/0/-1 etc) to indicate their status.

You can also write a getter method for the onCommand flag:

public string getFlag(){
  // some logic here
  return "green";

  // otherwise default to no flags
  return "";
}
Community
  • 1
  • 1
Husman
  • 6,819
  • 9
  • 29
  • 47
0

You could test that onCommand + "-green" has been written to System.out by using the System Rules library.

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72