'Testing Array element using Junit in Eclipse

I want to test if it adds all of the elements into the group array using Junit.

Here's the code:

public class Group{

private String groupName; 

    private ArrayList<Item> group = new ArrayList<Item>();

    public Group(String groupName) { 
        super();
        this.groupName = groupName;
    }
        
    public String getGroupName() {
        return groupName;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public void addItem(Item item) { 
        group.add(item);
    }
    public Item getItem(int index) {
        return group.get(index);
    }
    
    public String toString(boolean includePrice) {

        String string = "Group \"" + groupName + "\" contains...\n";
        for (int i = 0; i < group.size(); i++) {
            Item item = group.get(i); 
            String itemString = includePrice? item.toString() : item.getDisplayName();
            
            string = string + (i + 1) + ") " + itemString + "\n";
        }
        
        return string;
    }
}


Solution 1:[1]

There are 2 ways to test if addItem method adds all of the elements into the group array-

1st way

Create a method getItems like this

public List<Item> getItems() {
    return group;
}

and in the junit test call the getItems method to check if all the elements are added

@Test
void shouldAddAllItems1() {
    Group group = new Group("group1");
    List<Item> expectedItems = Arrays.asList(new Item("item1"), new Item("item2"));
    group.addItem(new Item("item1"));
    group.addItem(new Item("item2"));
    assertEquals(expectedItems, group.getItems());
}

2nd way

Use the getItem(int index) method to check if all the elements are added.

@Test
void shouldAddAllItems2() {
    Group group = new Group("group2");
    group.addItem(new Item("item1"));
    group.addItem(new Item("item2"));
    assertEquals(new Item("item1"), group.getItem(0));
    assertEquals(new Item("item2"), group.getItem(1));
}

Note: For both solutions, you will need to override the equals and hashcode methods in Item class for the equality check to work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ANKIT PRASAD