Ok I have got this code:
public void TraverseTree(TreeNode node) {
TraverseTree(node.getLeftChild());
System.out.println(node.getKey());
TraverseTree(node.getRightChild());
}
This actually traverses through the nodes of a tree and print them. I was about to write a test case when it dawned on me that how can you unit test a function with no return type?
After changing the code to make it ‘unit test’ worthy, it looks something like this:
public ArrayList<Object> TraverseTree(TreeNode node, ArrayList<Object> array) {
if(array == null)
array = new ArrayList<Object>();
traverseTree(node.getLeftChild(), array);
array.add(node.getKey())
traverseTree(node.getRightChild(), array);
return array;
}
Now I am thinking, is this the right way to do this? what about the fact that with every recursive call, there is an ArrayList object pushed up the stack? is this a good approach? what if the tree contains thousands of keys?
I really want to know is there a better way to do this? and is it possible to unit test my first code sample (the one which does not return anything)? my test cases are simply 1) is it returning in right order? what happens if the tree is null? etc
It’s only a reference (basically a pointer) that’s pushed on the stack.
An alternative strategy is to pass an abstract Stream object into your method, and have it print to that, rather than hardcoding it to
System.out. Then for testing, you can pass in a mock object for capturing the output.