I have written a method that is printing output to a console. How should I test it?
public class PrinterForConsole implements Printer<Item>{
public void printResult(List<Item> items) {
for (Item item: items){
System.out.println("Name: " + item.getName());
System.out.println("Number: " + item.getNumber());
}
}
}
currently, my test looks like this
public class TestPrinter{
@Test
public void printResultTest() throws Exception {
(am figuring out what to put here)
}
}
I have read the solution at this post (thanks @Codebender and @KDM for highlighting this) but don't quite understand it. How does the solution there test the print(List items) method? Hence, asking it afresh here.
The best way to test it is by refactoring it to accept a
PrintStream
as a parameter and you can pass anotherPrintStream
constructed out ofByteArrayOutputStream
and check what is printed into the baos.Otherwise, you can use
System.setOut
to set your standard output to another stream. You can verify what is written into it after the method returns.A simplified version with comments is below:
Note that if the
print
method throws an exception, theSystem.out
is not reset. It is better to usesetup
andteardown
methods to set and reset this.This is the Simple Test Code :-
For more :JUnit test for System.out.println()
How about something like this.
Eventually, what I came up with is this (after going through all the answers and links to possible duplicates above).
Read up on naming convention (shouldPrintToConsole()) for testing too. Wondering if this is the convention because I see many sites that follow and many that don't.
Since you have put you don't get what the duplicate question says, I will try to explain a little.
When you do,
System.setOut(OutputStream)
, whatever the application writes to the console (usingSystem.out.printX()
) statements, instead get written to theoutputStream
you pass.So, you can do something like,