mercredi 26 juillet 2017

Using JUnit to test a method that reverses a singly linked list

I'm implementing a singly linked list in Java. I've created a method called reverseList (see below) which reverses my list, for example:

head -> 1 -> 2 -> 3 -> null
Becomes:
head -> 3 -> 2 -> 1 -> null

I've also created a test class (using JUnit) that has a method called testReverseList (see below) which tests the reverseList method. The insert method takes the data and also the position in which you want to add a new node. All these three methods seems to be working correctly.

public String reverseList() {
    Node prev = null, current = head, next;
    StringBuilder checkList = new StringBuilder();
    while (current != null) {
        checkList.append(current.getData());
        next = current.getNext();
        current.setNext(prev);
        prev = current; 
        current = next;
    }
    head = current;
    return checkList.toString(); 
}

public void testReverseList() {
    LinkedList myList = new LinkedList();
    myList.insert(1, 1);
    myList.insert(2, 2);
    myList.insert(3, 3);
    String normalListOrder = "123";
    assertEquals("Check reverseList, reversing a list with 3 elements.", normalListOrder, myList.reverseList());    
}

My question is: I don't believe that I'm properly testing my reverseList method by using this approach of appending each data of my node and then returning it, because I'm not really checking if it was reversed or not. Furthermore, it looks like it would require more computational resources to do all this. And I don't think that just returning a true at the end of execution would be enough either. So, should I don't test it at all? Is there a better way to do the testing?

Aucun commentaire:

Enregistrer un commentaire