I have a double linked list in which i can perform various functions but I want to write JUnit tests to test those functionalities. I have written unit tests for testing operations like inserting node at end and head, but how to write a test for the insertion in between operation?
Thank you :)
Here is the my linked list and Test class
DoubleLinkedList.java
public class DoubleLinkedList {
Node head;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.prev = current;
}
}
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.data);
if (current.next != null)
System.out.print(" -> ");
current = current.next;
}
System.out.println();
}
public int size() {
int size = 0;
Node current = head;
while (current != null) {
size++;
current = current.next;
}
return size;
}
public void addIntoHead(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
head.prev = newNode;
newNode.next = head;
head = newNode;
}
}
public int returnHead() {
return head.data;
}
public void addInMiddle(int prevData, int data) {
Node current = head;
while (current != null) {
if (current.data != prevData) {
current = current.next;
} else{
break;
}
}
Node newNode = new Node(data);
newNode.next = current.next;
current.next.prev = newNode;
newNode.prev = current;
current.next = newNode;
}
}
DoubleLinkedListTest.java
import org.junit.Test;
import static org.junit.Assert.*;
public class DoubleLinkedListTest {
private DoubleLinkedList dll;
@org.junit.Before
public void setUp() throws Exception {
dll = new DoubleLinkedList();
}
@Test
public void shouldBeAbleToCreateANewNode() throws Exception {
int initialSizeBeforeAdd = dll.size();
dll.add(1);
dll.add(2);
assertEquals(initialSizeBeforeAdd+2,dll.size());
}
@Test
public void shouldAbleToAddIntoHead() throws Exception {
dll.add(1);
dll.add(2);
dll.addIntoHead(12);
assertEquals(0,dll.returnHead());
}
@Test
public void shouldAbleToAddDataInMiddle() throws Exception {
dll.add(1);
dll.add(2);
dll.add(4);
int size = dll.size();
dll.addInMiddle(2,3);
//what should be the assertion here.
}
}
Aucun commentaire:
Enregistrer un commentaire