简体   繁体   中英

unit test failing in java and not sure why

I have a method in class TreeUtils that checks for simalarity of structure between two binary search trees

if(root1 == null&& root2 == null)
    {
        return true;
    }
    if(root1 == null && root2!=null){
        return false;
    }
    if(root1 != null && root2 == null)
    {
        return false;
    }

    boolean leftRecurse = similar(root1.getLeft(), root2.getLeft());
    boolean rightRecurse = similar(root1.getRight(), root2.getRight());

    return leftRecurse && rightRecurse;

however when I run a unit test on this file it fails. But if I call this method from the main method, it works. Its not a package or scope issue, because the similar method works in the main method. I think it has something to do with

 public BinaryTreeNode getLeft() { 
    assert(this.hasLeft());
    return this.left; 
}

maybe because this is now a unit test it is calling the assert? how should I modify my similar method to avoid this.

This is my Unit test

public void testSimilar() {
    System.out.println("Test similarity");
    SimpleBST tree = new SimpleBST();
    tree.insert(1);
    tree.insert(2);
    SimpleBST tree2 = new SimpleBST();
    tree2.insert(1);
    tree2.insert(3);
    assertEquals(true, tree.similar(tree2));


}

thanks.

Assuming you have asserts enabled with -ea argument the program will throw an AssertionError if this does not have a left child. But by the setup you have, recursively you want to evaluate the left and right child even if they are null. Simply removing the assertion will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM