Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

create a set of unit tests, to test the behavior of the code written below. A unit test is an automated piece of code that

create a set of unit tests, to test the behavior of the code written below. A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work. Think of unit testing as a way to test the behavior of the code (or parts of the code) written, without actually having to run the program. For example, in the case of the code below, assume that the front-end (MainApp console user interface) part of the program and the back-end part of the program (ShippingStore database management) are written by two different developers. How would the developer of the back-end be able to ensure that the code he/she has written works correctly without having access to the front-end? You are asked to create JUnit tests to test the class ShippingStore, including all its methods. First you should consider testing the behavior of the class/methods under normal operation scenarios. For example, to test the method findPackageOrder(String trackingNumber) of the class ShippingStore, you may need to create a test method, which creates a mock PackageOrder object and adds it to the packageOrerList before the method findPackageOrder can be called to search for it. To ensure that everything worked as planned, you can then search for the package using its trackingNumber and see if the correct package is found. Mock objects can be created either in the same test method or before any test methods are run, using the @BeforeClass annotation. Subsequently, you can consider creating test cases for unusual scenarios, e.g. when a certain input or behavior is expected to cause an exception to be thrown, or when a user input is not as expected. At the end create a TestRunner class, which has a main method that runs the unit tests that you have created, and prints out the test results. Do not modify the code provided.

package shippingstore;

import java.io.IOException; import java.io.FileReader; import java.io.PrintWriter; import java.io.File; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Scanner;

/** * This class is used to represent a database interface for a list of * Package Order's. It using a plain-text file "PackageOrderDB.txt" * to store and write package order objects in readable text form. It contains * an ArrayList called packageOrerList to store the * database in a runtime friendly data structure. The packageOrerList * is written to "PackageOrderDB.txt" at the end of the ShippingStore object's * life by calling flush(). This class also provides methods for * adding, remove, and searching for shipping orders from the list. * * @author Junye Wen */ public class ShippingStore {

private final File dataFile; private ArrayList packageOrderList;

/** * This constructor is hard-coded to open "PackageOrderDB.txt" and * initialize the packageOrerList with its contents. If no such file * exists, then one is created. The contents of the file are "loaded" into * the packageOrerList ArrayList in no particular order. The file is then closed * during the duration of the program until flush() is called. * @throws IOException */ public ShippingStore() throws IOException { dataFile = new File("PackageOrderDB.txt"); packageOrderList = new ArrayList<>();

// If data file does not exist, create it. if (!dataFile.exists()) { System.out.println("Data file does not exist, creating one now . . ."); //if the file doesn't exists, create it PrintWriter pw = new PrintWriter(dataFile); //close newly created file so we can reopen it pw.close(); } } /** * Method that returns a reference to the data file. * @return dataFile */ public File getDataFile() { return dataFile; }

/** * Method showPackageOrer displays the current list of package orders in the Arraylist in no * particular order. * */ public void showPackageOrders() { showPackageOrders(packageOrderList); }

/** * Private method used as an auxiliary method to display a given ArrayList * of package orders in a formatted manner. * * @param orders the package order list to be displayed. */ private void showPackageOrders(ArrayList orders) {

System.out.println(" -------------------------------------------------------------------------- "); System.out.println("| Tracking # | Type | Specification | Class | Weight(oz) | Volume |"); System.out.println(" -------------------------------------------------------------------------- ");

for (int i = 0; i < orders.size(); i++) { System.out.println(String.format("| %-11s| %-8s| %-14s| %-12s| %-11s| %-7s|", orders.get(i).getTrackingNumber(), orders.get(i).getType(), orders.get(i).getSpecification(), orders.get(i).getMailingClass(), String.format("%.2f", orders.get(i).getWeight()), Integer.toString(orders.get(i).getVolume()) )); } System.out.println(" -------------------------------------------------------------------------- ");

}

/** * This method displays package orders that have a weight within the range of * low to high. * * @param low a float that is the lower bound weight. * @param high a float that is the upper bound weight. */ public void showPackageOrdersRange(float low, float high) { ArrayList orders = new ArrayList<>(); for (PackageOrder order : packageOrderList) { if ((low <= order.getWeight()) && (order.getWeight() <= high)) { orders.add(order); } } if (orders.isEmpty()) System.out.println("No packages found with weight within the given range. "); else showPackageOrders(orders); }

/** * This method can be used to find a package order in the Arraylist of orders. * * @param trackingNumber a String that represents the tracking number * of the order that to be searched for. * @return the int index of the package orders in the Arraylist of orders, * or -1 if the search failed. */ public int findPackageOrder(String trackingNumber) {

int index = -1;

for (int i = 0; i < packageOrderList.size(); i++) { String temp = packageOrderList.get(i).getTrackingNumber();

if (trackingNumber.equalsIgnoreCase(temp)) { index = i; break; }

}

return index; } /** * This method can be used to search for a package order in the Arraylist of orders. * * @param trackingNumber a String that represents the tracking number * of the order that to be searched for. */ public void searchPackageOrder(String trackingNumber) {

int index = findPackageOrder(trackingNumber);

if (index != -1) { ArrayList order = new ArrayList<>(1); order.add(getPackageOrder(index)); System.out.println(" Here is the order that matched: "); showPackageOrders(order); } else { System.out.println(" Search did not find a match. "); } }

/** * This method is used to add a package order to the orderList ArrayList. In order for a * package order to be added to the ArrayList it must comply with the following: *

* 1. The order is not already in the ArrayList according to the tracking number * as the unique key. *

* 2. The TrackningNumber string matches the following regular expression: * "[A-Za-z0-9]{5}" or in other words: it * is 5 alphanumeric characters. *

* 3. The Type of the order can be only one of the following: * Postcard, Letter, Envelope, Packet, Box, Crate, Drum, Roll, Tube. *

* 4. The Specification of the order can be only one of the following: * Fragile, Books, Catalogs, Do-not-Bend, N/A. *

* 5. The Mailing Class of the order can be only one of the following: * First-Class, Priority, Retail, Ground, Metro. *

* 6. The Weight must be non-negative. *

* 7. The Volume must be non-negative. * @param toAdd the PackageOrder object to add to the * packageOrerList */ public void addOrder(String trackingnumber, String type, String specification, String mailingclass, String weight, String volume) {

if (this.findPackageOrder(trackingnumber) != -1) { System.out.println("Package Order already exists in database. "); return; }

if (!trackingnumber.matches("[A-Za-z0-9]{5}")) { System.out.println("Invalid Tracking Number: not proper format." + "Tracking Number must be at least 5 alphanumeric characters."); return; }

if (!(type.equals("Postcard") || type.equals("Letter") || type.equals("Envelope") || type.equals("Packet") || type.equals("Box")|| type.equals("Crate") || type.equals("Drum")|| type.equals("Roll")|| type.equals("Tube"))) { System.out.println("Invalid type: " + "Type must be one of following: " + "Postcard, Letter, Envelope, Packet, Box, Crate, Drum, Roll, Tube."); return; }

if (!(specification.equals("Fragile") || specification.equals("Books") || specification.equals("Catalogs") || specification.equals("Do-not-Bend") || specification.toUpperCase().equals("N/A"))) { System.out.println("Invalid specification: " + "Specification must be one of following: " + "Fragile, Books, Catalogs, Do-not-Bend, N/A."); return; }

if (!(mailingclass.equals("First-Class") || mailingclass.equals("Priority") || mailingclass.equals("Retail") || mailingclass.equals("Ground") || mailingclass.equals("Metro")) ) { System.out.println("Invalid Mailing Class: " + "Mailing Class must be one of following: " + "First-Class, Priority, Retail, Ground, Metro."); return; }

if (Float.parseFloat(weight) < 0) { System.out.println("The weight of package cannot be negative."); return; }

if (!volume.matches("[0-9]{1,6}")) { System.out.println("Invalid volume: " + "The package's volume has to be an integer number between 0 and 999999. "); return; }

//If passed all the checks, add the order to the list packageOrderList.add(new PackageOrder(trackingnumber, type, specification, mailingclass, Float.parseFloat(weight), Integer.parseInt(volume))); System.out.println("Package Order has been added. "); }

/** * This method will remove an order from the packageOrerList ArrayList. It * will remove the instance of an order that matches tracking number that was * passed to this method. If no such order exists, it will produce an error message. * * @param toDelete the PackageOrder object to be removed. */ public void removeOrder(String trackingNum) { int orderID = findPackageOrder(trackingNum); if (orderID == -1) { System.out.println(" Action failed. No package order with the given tracking # exist in database. "); } else { packageOrderList.remove(orderID); System.out.println(" Action successful. Package order has been removed from the database. "); } }

/** * This method is used to retrieve the PackageOrder object from the * PackageOrderList at a given index. * * @param i the index of the desired PackageOrder object. * @return the PackageOrder object at the index or null if the index is * invalid. */ public PackageOrder getPackageOrder(int i) { if (i < packageOrderList.size() && i >= 0) { return packageOrderList.get(i); } else { System.out.println("Invalid Index. Please enter another command or 'h' to list the commands."); return null; } } /** * This method reads data from the FileReader provided as input and puts them * in the packageOrderList. * @param dataReader The input FileReader to read from. * @throws IOException If any problem occurs with the data input. */ public void read(Reader dataReader) throws IOException { Scanner orderScanner = new Scanner(dataReader);

//Initialize the Array List with package orders from PackageOrderDB.txt while (orderScanner.hasNextLine()) {

// split values using the space character as separator String[] temp = orderScanner.nextLine().split(" ");

packageOrderList.add(new PackageOrder(temp[0], temp[1], temp[2], temp[3], Float.parseFloat(temp[4]), Integer.parseInt(temp[5]))); }

//Package order list is now in the ArrayList completely so we can close the file orderScanner.close(); }

/** * This method accepts a Writer to a file and overwrites it with a text representation of * all the package orders in the PackageOrderList. * This should be the last method to be called before exiting the program. * @param dataWriter The data to write in the file. * @throws IOException */ public void flush(Writer dataWriter) throws IOException { for (PackageOrder c : packageOrderList) { dataWriter.write(c.toString()); }

dataWriter.close(); }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Generative Artificial Intelligence For Project Management With Aws

Authors: Timothy Krimmel

1st Edition

B0CQV9KWB8, 979-8872627197

More Books

Students also viewed these Databases questions