mardi 28 mars 2017

Mocking a List and attempting to iterate over it

Currently using Mockito to Test a method from one of my classes. My class contains a List, and the method takes in an object of the same class. The issue is when I attempt to iterate over the List from the object. I'm getting a null pointer to the list. Below you will see the code snippets.

private Shipment shipment;
private Shipment shipment2;
@Mock
private Order mockOrder1;
@Mock
private Order mockOrder2;
@Mock
private Order mockOrder3;
@Mock
private ArrayList<Order> mockShipmentOrders;
@Mock
private ArrayList<Order> mockShipmentOrders2;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
    mockShipmentOrders.add(mockOrder1);
    mockShipmentOrders.add(mockOrder2);
    mockShipmentOrders2.add(mockOrder3);
    shipment = new Shipment(1, mockShipmentOrders);
    shipment2 = new Shipment(2, mockShipmentOrders2);
}

@Test
public void test_mergeShipments_increasesByOneWhenAShipmentOfOneAddedToAShipmentORderSizeOfTwo(){
    shipment.mergeShipments(shipment2);
    assertEquals(3, shipment.getShipmentOrders().size());
}

above you can see my mockito test and below is my Class with the method:

public class Shipment {

private long shipmentID;
private List<Order> shipmentOrders;

public Shipment(long shipmentID, List<Order> shipmentOrders){
    this.shipmentID = shipmentID;
    this.shipmentOrders = shipmentOrders;
}

public List<Order> getShipmentOrders(){
    return shipmentOrders;
}

public void mergeShipments(Shipment shipment2){     
    List<Order> existingShipment = shipment2.getShipmentOrders();
    for (Order order : existingShipment){
        shipmentOrders.add(order);
    }
}

When I run the test I am getting a java.lang.NullPointerException for the line: for (Order order : existingShipment){ in mergeShipemts();

The question is; Is it possible to mock a list, call that list and then run a foreach over that mocked list?

Aucun commentaire:

Enregistrer un commentaire