Reputation: 5660
Many a times, technical interviewers ask questions such as 'print something'. Eg: http://www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/
The following code will ask to print all paths from root to leaf.
How do I unit test a code like this ?
One solution would be to return a datastructure will all paths. But then interviewer would rebuke me for consuming huge space complexity ?
Upvotes: 0
Views: 607
Reputation: 750
In the general case isolating a hard-to-test dependency (like console output) is the way to go. So in general, I'd do something along the lines of dasblinkenlight's suggestion. This also cleanly separates the responsibilities of calculating the tree and printing it out (be it after or during calculation), which makes your code arguably more maintainable.
In the very common case of System.out, there's an alternative that does not require changing the production code: you can capture the out stream in a string by using System.setOut. In the toy problem you provide, I would be tempted to take this shortcut.
Upvotes: 0
Reputation: 726559
One solution is to pass a PrintStream
to your method. When you call it from main
, pass System.out
, like this:
public static void main(String[] args) {
Tree tree = ...
TreePrinter printer = ...
printer.printTree(System.out);
}
When you call the method from your unit test code, pass it a subclass of PrintStream
, which collects the output in memory, and compares it to the expected output:
@Test
public void testTreePrinter() {
Tree tree = ...
TreePrinter printer = ...
MyTestStream testStream = ...
printer.printTree(testStream);
assertEquals(expectedOutput, testStream.collectedOutput());
}
Upvotes: 2