Search code examples
javaarraylistjunit4

Adding to an object ArrayList from another Class


I have a Class named Item.

public class Item {

private int code;
private String name;
private double price;
private int quantity;

public Item(int code, String name, double price, int quantity) {
    setCode(code);
    setName(name);
    setPrice(price);
    setQuantity(quantity);
}
//Item getters and setters

And I have a Class named Stock that creates an ArrayList of Items.

public class Stock {
private ArrayList<Item> stock;

public Stock() {
    stock = new ArrayList<Item>();
}

public ArrayList<Item> getStock() {
    return stock;
}

I also have a Class named ItemRegister that adds an Item to the Stock.

public class ItemRegister extends Stock {

public void registerItem(String name, double price) {
    getStock().add(new Item(setItemCode(), name, price, 0));
}

private int setItemCode() {
    return getStock().size() + 1;
}

I'm using unit tests to see if I did add an Item to the Stock.

public class ItemRegisterTest {

@Test
public void testIfHasRegisteredItemInStock() {
    Stock s = new Stock();
    assertTrue(s.getStock().size() == 0);
    ItemRegister i = new ItemRegister();        
    i.registerItem("Oleo", 20.0);
    assertTrue(s.getStock().size() == 1);
}

}

When I run these tests it is returning an error. On the second assertTrue, if I test with the object i it'll return true but what I want is to add to Stock and not ItemRegister because if later on I wanna consult Stock I'll call Stock and not ItemRegister.


Solution

  • I want is to add to Stock and not ItemRegister because if later on I wanna consult Stock I'll call Stock and not ItemRegister.

    Then you need to wrap Stock into ItemRegister.

    public class ItemRegister  {
        Stock stock;
        public ItemRegister(Stock stock) {
            this.stock = stock;
        }
    
        public void registerItem(String name, double price) {
            stock.getStock().add(new Item(setItemCode(), name, price, 0));
        }
    
        private int setItemCode() {
            return stock.getStock().size() + 1;
        }
    }
    

    Use it in your unit tests like this:

    public class ItemRegisterTest {
        @Test
        public void testIfHasRegisteredItemInStock() {
            Stock s = new Stock();
            assertTrue(s.getStock().size() == 0);
            ItemRegister i = new ItemRegister(s);        
            i.registerItem("Oleo", 20.0);
            assertTrue(s.getStock().size() == 1);
        }
    }