Reputation: 11
I'm trying to use Junit to verify that something output by a method matches a string using assertequals, but I can't get it to work. Because it says that the test case is undefined for (String, Void) My code for the method is below
public void speciesInformation() {
switch (species){
case"Penguin":System.out.println("Penguin Trivia fact");
break;
default: System.out.println("There is no current information for that species");
break;
}
}
and the junit code I'm attempting to use is(other tests omitted):
public class AnimalsTest extends junit.framework.TestCase{
public void testSpeciesInfo() {
assertEquals(" Penguin Trivia fact/n", penguin.speciesInformation());
}
}
All my other tests work because they're based on a return, but this one is supposed to be based on what's printed by the public void method and I can't tell how to do it or find information on how.
Upvotes: 1
Views: 1086
Reputation: 6839
In general, it's not always easy to assert some things, especially if they are static methods.
In this case, you can set another Stream
for the System.out
, what is explained in another answer.
However, if we talk about testing in general, you should ask yourself: "What do I really need to test?" Actually, you probably want to test that correct string was printed, right? So:
You can check the second one using the tool you've already mentioned - asserting correctness of a method, returning a string. To do this, you can refactor your method a bit:
public void speciesInformation() {
System.out.println(getSpeciesInforationText(species));
}
public void getSpeciesInforationText(String species) {
switch (species){
case"Penguin":
return "Penguin Trivia fact");
default:
return "There is no current information for that species");
}
}
This way you can easily test the getSpeciesInforationText
correctness.
And the first method becomes very simple - you just call print
method there. As a result you can either not test it all (because it's very simple) or you can use a technique called Mocking to test that you called the method. But it will require much more actions from your side. If you are interested in it, check out what Mockito
is and how to use it.
Upvotes: 1
Reputation: 13
You can use ByteArrayOutputStream
for this, set new PrintStream
of byteArrayOutputStream
in System.setOut
, then you can assert what was logged in console easily.
Upvotes: 1