dimanche 6 janvier 2019

JUnit for testing the reversion of a Singly Linked List

I need to write JUnits in order to test the reverse method of a singly linked list. This is the code I have for the link list

 class LinkedList { 

   static Node head; 

   static class Node { 

    int data; 
    Node next; 

    Node(int d) { 
        data = d; 
        next = null; 
     } 
  } 

/* Function to reverse the linked list */
Node reverse(Node node) { 
    Node prev = null; 
    Node current = node; 
    Node next = null; 
    while (current != null) { 
        next = current.next; 
        current.next = prev; 
        prev = current; 
        current = next; 
    } 
    node = prev; 
    return node; 
  } 

  // prints content of double linked list 
  void printList(Node node) { 
    while (node != null) { 
        System.out.print(node.data + " "); 
        node = node.next; 
    } 
  } 

    public static void run(ReverseLinkedList list, Node head) {
   head = list.reverse(head);
   list.printList(head);
   }
public static void main(String[] args) { 
    ReverseLinkedList list = new ReverseLinkedList(); 
    list.head = new Node(85); 
    list.head.next = new Node(15); 
    list.head.next.next = new Node(4); 
    list.head.next.next.next = new Node(20);
    run(list, head);
    }
  } 

Now I want to make JUnits in order to test the reverse method, but I I am not sure how I should do it. Should I refactor the code somehow to achieve this? So far, this is what is in my test class:

 import static org.junit.jupiter.api.Assertions.*;

 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;

 import ReverseLinkedList.Node;

class ReverseLinkedListTest {

@BeforeEach
void setUp() throws Exception {
}

@Test
void testReversion() {
    ReverseLinkedList list = new ReverseLinkedList(); 
    list.head = new Node(85); 
    list.head.next = new Node(15); 
    list.head.next.next = new Node(4); 
    list.head.next.next.next = new Node(20); 

} }

But my test class does not even compile, I get the following error:

    Multiple markers at this line
   - Node cannot be resolved to a type
   - The static field ReverseLinkedList.head should be accessed in a 
     static way

Aucun commentaire:

Enregistrer un commentaire