我一直致力于在没有明确拥有迭代器的二叉搜索树上实现JUnit测试。代替迭代器,这个树有一个名为getNext()的方法,我认为这个方法与while循环串联,我可以在测试中测试树而没有错误。问题是我不知道如何在我的测试中实现while循环以使我的测试工作。
public class BinarySearchTree<T extends Comparable<T>> implements
BSTInterface<T> {
protected BSTNode<T> root;
boolean found;
protected LinkedUnbndQueue<T> inOrderQueue; // queue of info
protected LinkedUnbndQueue<T> preOrderQueue; // queue of info
protected LinkedUnbndQueue<T> postOrderQueue; // queue of info
public BinarySearchTree()
{
root = null;
}
private T recGet(T element, BSTNode<T> tree)
{
if (tree == null)
return null; // element is not found
else if (element.compareTo(tree.getInfo()) < 0)
return recGet(element, tree.getLeft()); // get from left subtree
else if (element.compareTo(tree.getInfo()) > 0)
return recGet(element, tree.getRight()); // get from right subtree
else
return tree.getInfo(); // element is found
}
public T get(T element)
// Returns an element e from this BST such that e.compareTo(element) == 0;
// if no such element exists, returns null.
{
return recGet(element, root);
}
private T getPredecessor(BSTNode<T> tree)
// Returns the information held in the rightmost node in tree
{
while (tree.getRight() != null)
tree = tree.getRight();
return tree.getInfo();
}
private void inOrder(BSTNode<T> tree)
// Initializes inOrderQueue with tree elements in inOrder order.
{
if (tree != null) {
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode<T> tree)
// Initializes preOrderQueue with tree elements in preOrder order.
{
if (tree != null) {
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode<T> tree)
// Initializes postOrderQueue with tree elements in postOrder order.
{
if (tree != null) {
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
public T getNext(int orderType)
{
if (orderType == INORDER)
return inOrderQueue.dequeue();
else if (orderType == PREORDER)
return preOrderQueue.dequeue();
else if (orderType == POSTORDER)
return postOrderQueue.dequeue();
else
return null;
}
我已经删除了常用的添加,删除和包含树中的方法以节省空间。我正在运行的测试使用TestCase和TestRunner。到目前为止,我所拥有的测试只是简单的添加,删除,大小和包含测试。任何意见都将不胜感激。
答案 0 :(得分:0)
构建树后,测试中会有一个BinarySearchTree<SomeType>
类型的对象。
然后你可以调用getNext
直到它返回null(正如你在评论中所说的那样)
BinarySearchTree<SomeType> tree;
...
SomeType data;
while ((data = tree.getNext()) != null) {
//do whatever assertion you want to do with the returned data.
}