Testing with JUnit's void method

I have the following code and I don't know how to test it.

I tried to access the contD ++ account and if I have 3 negatives.

I cannot test it with something like this assertEquals(contD,3)

public void listarD() {
    int contD = 0;

    for(int i=0; i< clientes.length; i++) {
        if(clientes[i].getSaldo() < 0) {
            System.out.println(
                    "Cliente: " + clientes[i].getNombre() + 
                    ". Saldo: " + clientes[i].getSaldo());
            contD++;
        }
    }

    if (contD == 0) {
        System.out.println("No hay descubiertos :D");
    }
    else {
        System.out.println("TOTAL DESCUBIERTOS: " + contadorDescubiertos + " clientes");
    }       
}

      

+3


source to share


4 answers


The correct way is to retrieve a method that calculates the value contD

and checks it.

public void listarD() {

    int contD = calculateContD();

    if (contD == 0) {
        ...
    }    
}

      



And then you can test this method calculateContD()

.

+3


source


A well-designed method should be easy to test, the fact that you cannot test your method is proof of a design flaw.

Some suggestions:



  • Make the result of the method verifiable (this may mean that it is no longer valid).
  • Leave the output to permanent storage such as disk or a database.
+3


source


There is one way to theoretically test this: modify the object behind System.out.

So, in theory, you could put a "special" OutputStream in System.out; run your void method; and then check that the messages you are expecting ... appear in your thread.

But it just doesn't make any sense: you see that in the real world you rarely type to system.out. In the real world, your methods are either

  • return value
  • makes calls to other objects
  • change any internal state of the object / class object

Thus: in the real world, you write tests that take care of such events.

So how did you understand yourself; the real answer is to change the behavior of your void method; returning an already computed value!

+2


source


In general, a function that can only be tested with human eyes is not a good design. Callers will never know what happened after they called your feature. Either a return value or an exception is better than nothing to indicate the result.

0


source







All Articles