JUnit для методов ListADT isEmpty () и removeAll () не работают при добавлении одного или нескольких элементов - PullRequest
0 голосов
/ 10 апреля 2019

При тестировании методов isEmpty и removeAll для метода Unsorted List с использованием JUnit все тесты приводят к исключениям пустых указателей.

Я попытался создать метод, расширяющий метод Unsorted List, и он работаетпри использовании нулевого теста, но впоследствии дает исключения нулевого указателя.С помощью теста метода removeAll все они дают исключение пустого указателя.

ArrayUnsortedList:

//----------------------------------------------------------------------------
// ArrayUnsortedList.java         by Dale/Joyce/Weems                Chapter 6
//
// Implements the ListInterface using an array.
//
// Null elements are not permitted on a list.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the 
// original capacity.
//----------------------------------------------------------------------------

package lists;

public class ArrayUnsortedList<T> implements ListInterface<T>  
{
  protected final int DEFCAP = 100; // default capacity
  protected int origCap;            // original capacity
  protected T[] list;               // array to hold this list’s elements
  protected int numElements = 0;    // number of elements in this list
  protected int currentPos;         // current position for iteration

  // set by find method
  protected boolean found;  // true if element found, otherwise false
  protected int location;   // indicates location of element if found

  public ArrayUnsortedList() 
  {
    list = (T[]) new Object[DEFCAP];
    origCap = DEFCAP;
  }

  public ArrayUnsortedList(int origCap) 
  {
    list = (T[]) new Object[origCap];
    this.origCap = origCap;
  }

  protected void enlarge()
  // Increments the capacity of the list by an amount 
  // equal to the original capacity.
  {
    // Create the larger array.
    T[] larger = (T[]) new Object[list.length + origCap];

    // Copy the contents from the smaller array into the larger array.
    for (int i = 0; i < numElements; i++)
    {
      larger[i] = list[i];
    }

    // Reassign list reference.
    list = larger;
  }

  protected void find(T target)
  // Searches list for an occurence of an element e such that
  // e.equals(target). If successful, sets instance variables
  // found to true and location to the array index of e. If
  // not successful, sets found to false.
  {
    location = 0;
    found = false;

    while (location < numElements) 
    {
      if (list[location].equals(target))
      {  
        found = true;
        return;
      }
      else
        location++;
    }
  }

  public void add(T element)
  // Adds element to this list.
  {
    if (numElements == list.length)
      enlarge();
    list[numElements] = element;
    numElements++;
  }

  public boolean remove (T element)
  // Removes an element e from this list such that e.equals(element)
  // and returns true; if no such element exists, returns false.
  {
    find(element);    
    if (found)
    {
      list[location] = list[numElements - 1];
      list[numElements - 1] = null;
      numElements--;  
    }
    return found;
  }

  public int size()
  // Returns the number of elements on this list. 
  {
    return numElements;
  }

  public boolean contains (T element)
  // Returns true if this list contains an element e such that 
  // e.equals(element); otherwise, returns false.
  {
    find(element);
    return found;
  }

  public T get(T element)
  // Returns an element e from this list such that e.equals(element);
  // if no such element exists, returns null.
  {
    find(element);    
    if (found)
      return list[location];
    else
      return null;
  }

  public String toString()
  // Returns a nicely formatted string that represents this list.
  {
    String listString = "List:\n";
    for (int i = 0; i < numElements; i++)
      listString = listString + "  " + list[i] + "\n";
    return listString;
  }

  public void reset()
  // Initializes current position for an iteration through this list,
  // to the first element on this list.
  {
    currentPos  = 0;
  }

  public T getNext()
  // Preconditions: The list is not empty
  //                The list has been reset
  //                The list has not been modified since the most recent reset
  //
  // Returns the element at the current position on this list.
  // If the current position is the last element, it advances the value 
  // of the current position to the first element; otherwise, it advances
  // the value of the current position to the next element.
  {
    T next = list[currentPos];
    if (currentPos == (numElements - 1))
      currentPos = 0;
    else
      currentPos++;
    return next;
  }

  public boolean isEmpty() {
      if(list == null || list.length == 0) {
            return true;
        }
        else
            return false;
  }

  public int removeAll(T element)
  {
      int count = 0;
      find(element);
      while (found)
      {
          find(element);
          list[location] = list[numElements - 1];
          list[numElements - 1] = null;
          numElements--;  
          count ++;
        }
      return count;
  }

}

Тесты:

isEmpty:

package testList;

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

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

import ApplicationLevelMethods.Methods;
import lists.ArrayUnsortedList;


class Test_AppLevel_isEmpty {

    ArrayUnsortedList<String> testNull, testOne, testMult;

    @Before
    public void setUp() {
        testNull = new ArrayUnsortedList<String>();
        testOne = new ArrayUnsortedList<String>();
        testMult = new ArrayUnsortedList<String>();
    }

    @Test
    public void test_null() {
        assertTrue(testNull.isEmpty());
            }

    @Test
    public void test_one() {
        testOne.add("one");
        assertFalse(testOne.isEmpty());
    }

    @Test 
    public void test_multiple() {
        testMult.add("one");
        testMult.add("two");
        testMult.add("three");
        assertFalse(testMult.isEmpty());
    }
}

removeAll:

package testList;

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

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

import lists.ArrayUnsortedList;

class Test_AppLevel_removeAll {

    ArrayUnsortedList<String> testNull, testOne, testMult;

    @Before
    public void setUp() {
        testNull = new ArrayUnsortedList<String>();
        testOne = new ArrayUnsortedList<String>();
        testMult = new ArrayUnsortedList<String>();
    }

    @Test
    void test_Null() {
        testNull.removeAll("one");
        assertEquals(0,testNull.removeAll("one"));
    }

    @Test
    void test_One() {
        testOne.add("one");
        assertEquals(1,testOne.removeAll("one"));
    }

}

1 Ответ

0 голосов
/ 10 апреля 2019

Проблема в том, что вы смешиваете аннотации для JUnit 4 и JUnit 5.

Вы получаете NPE, потому что тесты выполняются как тесты JUnit 5, но аннотация @Before относится только к JUnit 4. JUnit 5 не распознает аннотацию @Before и поэтому не распознает setUp как метод, который нужно вызывать перед каждым тестом, поэтому не вызывайте его.

Исправление заключается в замене аннотации JUnit 4 @Before на аннотацию JUnit 5 @BeforeEach. См. Также раздел «Советы по миграции» в документации по JUnit 5 .

Test_AppLevel_removeAll также включает в себя строку import static org.junit.Assert.assertEquals;: удалите ее, поскольку в классе JUnit 5 Assertions есть метод assertEquals.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...