Writing unit tests (JUnit) for a class that manipulates an ArrayList of objects. Is it possible to directly test the contents of that ArrayList, or do I just need to test the function that returns formatted information from ArrayLists and use that to test the rest of the program? (code below)
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class HardeWareStore {
private ArrayList<Item> itemList;
public HardwareStore() throws IOException {
itemList = new ArrayList<>();
}
public String getAllItemsFormatted() {
return getFormattedItemList(itemList);
}
private String getFormattedItemList(ArrayList<Item> items) {
String text = " ------------------------------------------------------------------------------------\n" +
String.format("| %-10s| %-25s| %-20s| %-10s| %-10s|%n", "ID Number", "Name", "Category", "Quantity", "Price") +
" ------------------------------------------------------------------------------------\n";
for (int i = 0; i < items.size(); i++) {
text += String.format("| %-10s| %-25s| %-20s| %-10s| %-10s|%n",
items.get(i).getIdNumber(),
items.get(i).getName(),
items.get(i).getCategory(),
Integer.toString(items.get(i).getQuantity()),
String.format("%.2f", items.get(i).getPrice()));
}
text += " ------------------------------------------------------------------------------------\n";
return text;
}
public void addNewItem(String idNumber, String name, String category, int quantiy, float price) {
//If passed all the checks, add the item to the list
itemList.add(new Item(idNumber, name, category, quantiy, price));
System.out.println("Item has been added.\n");
}
(This is an assignment, so changing the source code in any way is not an option)
Is there any way for a test class to know what is in "itemList", so I can test the "addNewItem" method without relying on another method like "getFormattedItemList"?