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");
}
}
source to share
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.
source to share
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!
source to share