Issue
I use a factory pattern. I have 3 currencies: dollars, RON and euro. In each of this classes i have the same function, print, with different output:
public void print() {
System.out.println("I printed dollars!");
}
public void print() {
System.out.println("I printed euro!");}
In my factory class, i have a method that return a new Object of currency type:
public Valuta getValuta(String numeValuta){
if(numeValuta == null){
return null;
}
if(numeValuta.equalsIgnoreCase("dolar")){
return new Dolar();
}
if(numeValuta.equalsIgnoreCase("euro")){
return new Euro();
}
if(numeValuta.equalsIgnoreCase("lei")){
return new Lei();
}
return null;
}
Now, in my Test class, i tried testing this:
FabricaBani fabrica = new FabricaBani();
Valuta valuta = fabrica.getValuta("dolar");
valuta.tipareste();
assertEquals("I printed dollars!", valuta.print());
I get an error that says that i cannot test a String with a void. I tried putting .toString after valuta.print, but i am not allowed.
Solution
The method valuta doesn't return anything, that's why valuta.print() can't be the String you output to the console.
If you want to test the value, you could refactor your method to return the String instead of outputting it; then you'd print the returned String in the method that calls print().
public String print() {
return "I printed dollars!";
}
public void print() {
return "I printed euro!";
}
Then, you'd call the print like this to output to console
System.out.println(valuta.print());
You can maybe rename the print method to getCurrency to better express what the method does.
Answered By - Jihed Amine