2016-02-26 18 views
0

Я нахожусь в Eclipse Java Mars, и у меня возникают некоторые трудности с тестированием JUnit. Я тестирую свой класс QueueADT, который я реализовал с помощью Linked List. Я приложу все 3 кода.JUnit testing java eclipse

Проблема в том, что я продолжаю получать исключение NullPointer для всех методов в тесте JUnit.

линий, которые дают ошибки в очереди тестирования являются: Все являются линии с "q.enqueue" линии 29 линии 56 линии 67 линии 45 линии 12 линии 73 линии 36 линии 20

QueueADT код:

/** 
* QueueADT defines the interface to a queue collection. 
*/ 
public interface QueueADT<String> 
{ 
/** 
* Adds one element to the rear of this queue. 
* @param element the element to be added to the rear of the queue 
*/ 
public void enqueue(String element); 

/** 
* Removes and returns the element at the front of this queue. 
* @return the element at the front of the queue 
*/ 
public String dequeue() throws CollectionUnderflowException; 

/** 
* Returns without removing the element at the front of this queue. 
* @return the first element in the queue 
*/ 
public String first() throws CollectionUnderflowException; 

/** 
* Returns true if this queue contains no elements. 
* @return true if this queue is empty 
*/ 
public boolean isEmpty(); 

/** 
* Returns the number of elements in this queue. 
* @return the integer representation of the size of the queue 
*/ 
public int size(); 

/** 
* Returns a string representation of this queue. 
* @return the string representation of the queue 
*/ 
public String toString(); 
} 

LinkedListQueue код:

/** 
* LinkedQueue represents a singly linked list implementation of a Queue. 

*/ 
import java.util.*; 

public class LinkedQueue<String> implements QueueADT<String> 
{ 
private int count;    // the number of items in the queue 
private Node<String> head, tail; // references to the first and last nodes in the queue 

/** 
* Creates an empty queue. 
*/ 
public LinkedQueue() 
{ 
    count = 0; 
    head = tail = null; 
} 

/** 
* Adds the specified element to the tail of this queue. 
* @param element the element to be added to the tail of the queue 
*/ 
public void enqueue(String element) 
{ 
    Node<String> node = new Node<String>(element); 

    if (isEmpty()) 
     head = node; 
    else 
     tail.next = node; 

    tail = node; 
    count++; 
} 

/** 
* Removes the element at the head of this queue and returns a 
* reference to it. 
* @return the element at the head of this queue 
* @throws CollectionUnderflowException if the queue is empty 
*/ 
public String dequeue() throws CollectionUnderflowException 
{ 
    if (isEmpty()) 
     throw new CollectionUnderflowException("Queue is empty."); 

    String result = head.element; 
    head = head.next; 
    count--; 

    if (isEmpty()) 
     tail = null; 

    return result; 
} 

/** 
* Returns a reference to the element at the head of this queue. 
* The element is not removed from the queue. 
* @return a reference to the first element in this queue 
* @throws CollectionUnderflowException if the queue is empty 
*/ 
public String first() throws CollectionUnderflowException 
{ 
    if (isEmpty()) 
    throw new UnsupportedOperationException("Not yet implemented."); 

    return head.getElement(); 
} 

/** 
* Returns true if this queue is empty and false otherwise. 
* @return true if this queue is empty 
*/ 
public boolean isEmpty() 
{ 
    return(count == 0); 
    //throw new UnsupportedOperationException("Not yet implemented."); 
} 

/** 
* Returns the number of elements currently in this queue. 
* @return the number of elements in the queue 
*/ 
public int size() 
{ 
    return count; 
    //throw new UnsupportedOperationException("Not yet implemented."); 

} 

/** 
* Returns a string representation of this queue. 
* @return the string representation of the queue 
*/ 
public String toString() 
{ 
    String finish = " "; 
    Node<String> recent = head; 

    while (recent != null){ 
     finish = finish + (recent.getElement()).tostring() + "\n"; 
     recent = recent.getNext(); 
    } 
    //throw new UnsupportedOperationException("Not yet implemented."); 
} 


    private static class Node<E> { 
E element; 
Node<E> next; 

public Node(E element) { 
    this.element = element; 
    } 
    } 
} 

JUnit код теста:

import junit.framework.TestCase; 

public class QueueT extends TestCase { 

     /** 
     * The queue to use in all the tests: set this in subclasses. 
     */ 
     protected QueueADT q; 

     @Test 
     public void testNewQueueIsEmpty() { 
      assertTrue(q.isEmpty()); 
      assertEquals(q.size(), 0); 
     } 

     // @Test 
     public void testInsertsToEmptyQueue() { 
      int numberOfInserts = 6; 
      for (int i = 0; i < numberOfInserts; i++) { 
       q.enqueue("zzz"); 
      } 
      assertTrue(!q.isEmpty()); 
      assertEquals(q.size(), numberOfInserts); 
     } 

     //@Test 
     public void testEnqueueThenDequeue() { 
      String message = "hello"; 
      q.enqueue(message); 
      assertEquals(q.dequeue(), message); 
     } 

     // @Test 
     public void testEnqueueThenPeek() { 
      String message = "hello"; 
      q.enqueue(message); 
      int size = q.size(); 
      assertEquals(q.first(), message); 
      assertEquals(q.size(), size); 
     } 

     // @Test 
     public void testFiftyInThenFiftyOut() { 
      for (int i = 0; i < 50; i++) { 
       q.enqueue(i); 
      } 
      for (int i = 0; i < 50; i++) { 
       assertEquals(((Integer)q.dequeue()).intValue(), i); 
      } 
     } 

     // @Test 
     public void testRemovingDownToEmpty() { 
      int numberOfRemoves = (int)(Math.random() * 20 + 1); 
      for (int i = 0; i < numberOfRemoves; i++) { 
       q.enqueue("zzz"); 
      } 
      for (int i = 0; i < numberOfRemoves; i++) { 
       q.dequeue(); 
      } 
      assertTrue(q.isEmpty()); 
      assertEquals(q.size(), 0); 
     } 

     // @Test(expected=NoSuchElementException.class) 
     public void testRemoveOnEmptyQueue() { 
      assertTrue(q.isEmpty()); 
      q.dequeue(); 
     } 

     //@Test(expected=NoSuchElementException.class) 
     public void testPeekIntoEmptyQueue() { 
      assertTrue(q.isEmpty()); 
      q.dequeue(); 
     } 


} 
+0

Какие строки вызывают исключение? – TangledUpInBlue

+0

oh извините. Я отредактирую сообщение и поставлю строки! – isabella

+0

в порядке. сделано, извините за что. – isabella

ответ

1

Создать набор Up Method

@Before 
public void setUp() { 
    q = new LinkedQueue(); 
} 

который будет инициализировать вас Q объект перед каждым испытанием или

@BeforeClass 
public static void setUp() { 
    q = new LinkedQueue(); 
} 

, если вы хотите только один общий объект между всеми испытаниями.

На стороне примечания: Я действительно не вижу никаких выгод от вашей пользовательской коллекции, поскольку LinkedList, похоже, соответствует вашим целям.

0

Вы пропускаете установку() и партер() метод!

1

Вы получаете NullPointerException, потому что ваш объект protected QueueADT q; никогда не инициализируется в классе QueueT.