链接列表测试…返回类型问题

问题描述 投票:0回答:2

我有此代码的IntLinkedList类

public class IntLinkedList {

    private Node head;

    public void addFirst(int data) {
        head = new Node(data, head);
    }

    public Node copy(){
       Node current = head; // used to iterate over original list
       Node newList = null; // head of the new list
       Node tail = null;    // point to last node in new list

       while (current != null)
       {
        // special case for the first new node
          if (newList == null)
          {
              newList = new Node(current.data, null);
              tail = newList;
          }
          else
          {
              tail.next = new Node(current.data, null);
              tail = tail.next;
          }
          current = current.next;
       }
       return newList;
    }


    private class Node  {
            int data;
            Node next;

        Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}

并且我正在尝试使用以下JUnit代码测试copy方法

public class IntLinkedListTest {

    /** Reference to linked list under test */
    private IntLinkedList lst;

    /** Creates a linked list for testing. */
    @Before
    public void setUp() {
        lst = new IntLinkedList();

        lst.addFirst(30);
        lst.addFirst(10);
        lst.addFirst(40);
        lst.addFirst(20);
    }

    /** Tests copying a non-empty list. */
    @Test
    public void testCopy() {
        IntLinkedList cpy = lst.copy();
        assertEquals(lst.toString(), cpy.toString());
    }
}

我想从Copy()方法获得IntLinkedList类返回的列表,并在JUnit中对其进行测试。我也尝试返回IntLinkedList和Object类型,但是我不断收到诸如“类型不匹配:无法从IntLinkedList.Node转换为IntLinkedList”之类的错误。我对LinkedList的经验很少,但是对Java类,对象的引用却很有经验,但这对我来说是新领域。有人可以帮忙吗?

java class junit linked-list singly-linked-list
2个回答
0
投票

Solution:-您正在将Node类toString与IntLinkedList类toString进行比较,从而导致Junit失败,尝试覆盖Node和IntLinkedList类的toString()方法,您会清楚地看到堆栈跟踪为] >

org.junit.ComparisonFailure: expected:<[IntLinkedList [head=Node [data=20, next=Node [data=40, next=Node [data=10, next=Node [data=30, next=null]]]]]]> but was:<[Node [data=20, next=Node [data=40, next=Node [data=10, next=Node [data=30, next=null]]]]]>

此Junit正常工作

 @Test
    public void testCopy() {
        IntLinkedList.Node cpy = lst.copy();
        assertEquals(lst.copy().toString(), cpy.toString());
    }

编辑

:-因为您的Node类是私有的,所以我做了一个较小的更改以使IntLinkedList.Node工作,因此我将签名更改为static以使junit工作,即
static class Node  {

0
投票

© www.soinside.com 2019 - 2024. All rights reserved.