Почему я получаю исключение нулевого указателя при добавлении элемента в ArrayList - PullRequest
0 голосов
/ 07 марта 2020

У меня есть мой класс предписания следующим образом:

import java.util.ArrayList;
import java.util.List;

public class Prescription {

    private final ArrayList<Product> prescriptionItems = new     ArrayList<Product>();
    private long prescriptionId;

    public List<Product> getPrescriptionItems() {
        return prescriptionItems;
    }

    public void addPrescriptionItem(final Product product) {
        this.prescriptionItems.add(product);
    }
}

У меня есть класс продукта следующим образом

public class Product {

    public Product(final long productCode, final double productCost) {
        this.productCode = productCode;
        this.productCost = productCost;
    }


    private final long productCode;
    private final double productCost;

    public long getProductCode() {
        return productCode;
    }

      public double getProductCost() {
        return productCost;
       }
}

У меня есть мои настройки теста следующим образом:
У меня есть мой Метод настройки следующим образом:

        @BeforeEach
    void setUp() throws Exception 
        {
            medAvailControllerImpl = new MedAvailControllerImpl(medAvailDAO, dispenser, paymentHandlerFactory);
        prescriptionProduct = new Product(789, 44.0);
        customer = new Customer(45678, "Amofa Baffoe", "Claregalway", "kbaffoe@hotmail.com", "paypal", paypalStrategy);
        when(medAvailDAO.getCustomerForId(45678)).thenReturn(customer);
    }

У меня есть мой тест JUnit / Mockito следующим образом:

    @Test
    public void testOneItemOnPrescriptionSuccess() throws Exception {
        //prescriptionProduct = new Product(789, 44.0);
        prescriptionItems.add(prescriptionProduct);
            when(prescription.getPrescriptionItems()).thenReturn(prescriptionItems);

    }

Я получаю NullPointerException, где prescriptionItems добавляется к prescriptionProduct. Любая помощь?

Ответы [ 2 ]

0 голосов
/ 09 марта 2020

попробуйте инициализировать prescriptionItems ArrayList:

private ArrayList <Product> prescriptionItems;

до

private ArrayList <Product> prescriptionItems = new ArrayList<Product>(); 

, когда вы объявили его в коде теста.

Кстати, почему вы добавляете новый ArrayList для продуктов, если вы хотите протестировать добавление продукта с помощью метода addPrescriptionItem внутри prescription класса, который добавляет продукт в ArrayList, уже определенный в классе Prescription.

0 голосов
/ 08 марта 2020

Я попытался воспроизвести ваш код на моем компьютере, и он сработал, добавил продукт и без ошибок возвратил его, используя List<Product> getPrescriptionItems().

import java.util.ArrayList; 
import java.util.List;

class Product {
    public Product(final long productCode, final double productCost) {
        this.productCode = productCode;
        this.productCost = productCost;
    }


    private final long productCode;
    private final double productCost;

    public long getProductCode() {
        return productCode;
    }

      public double getProductCost() {
        return productCost;
      }
}  
public class Prescription {

    private final ArrayList<Product> prescriptionItems = new ArrayList<Product>();
    private long prescriptionId;

    public List<Product> getPrescriptionItems() {
        return prescriptionItems;
    }

    public void addPrescriptionItem(final Product product) {
        this.prescriptionItems.add(product);
    }


    public static void main(String[] args) {

        // instantiate Prescription
        Prescription pres = new Prescription();

        // add a product to ArrayList using addPrescriptionItem()
        pres.addPrescriptionItem(new Product(50, 15.0));

        // get the product details from the ArrayList
        Product product = pres.getPrescriptionItems().get(0);

        System.out.println(product.getProductCode()+ " " + product.getProductCost()); // will print "name in sup Class"
    }
}

Вот вывод: the output

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