Question

In: Computer Science

You must write tests for the following: all tests must be written in JUnit 5. Customer...

You must write tests for the following:

all tests must be written in JUnit 5.

  • Customer Class
    • Checking that the customer number autoincrements with each new customer object created
  • Order Class
    • Checking that the order number autoincrements with each new order object created
    • Adding a product that is already in the order
    • Removing a product that is in the order - quantity less than the quantity in the order
    • Removing a product that is in the order - quantity that is greater than or equal to the quantity in the order
    • ===================================================
    • the code for the java classes
    • public class Customer {
      
              private static int nextNumber = 1;
              private int number;
              private String firstName;
              private String lastName;
              
              /**
               * Represents a customer with customer number (autogenerated), first and last name.
               * @param firstName
               * @param lastName
               */
              public Customer(String firstName, String lastName) {
                      this.number = nextNumber++;
                      this.firstName = firstName;
                      this.lastName = lastName;
              }
      
              /**
               * Returns the first name
               * @return the first name
               */
              public String getFirstName() {
                      return firstName;
              }
      
              /**
               * Returns the last name
               * @return the last name
               */
              public String getLastName() {
                      return lastName;
              }
              
              /**
               * Sets the first name
               * @param firstName
               */
              public void setFirstName(String firstName) {
                      this.firstName = firstName;
              }
              
              /**
               * Sets the last name
               * @param lastName
               */
              public void setLastName(String lastName) {
                      this.lastName = lastName;
              }
              
              /**
               * Returns the customer number
               * @return the customer number
               */
              public int getNumber() {
                      return number;
              }
      
              @Override
              public String toString() {
                      return "Customer [number=" + number + ", name=" + firstName + " " + lastName + "]";
              }
      
              /** 
               * Customers are equal *only* if their customer numbers are equal
               * @see java.lang.Object#equals(java.lang.Object)
               */
              @Override
              public boolean equals(Object obj) {
                      if (this == obj)
                              return true;
                      if (obj == null)
                              return false;
                      if (getClass() != obj.getClass())
                              return false;
                      Customer other = (Customer) obj;
                      if (number != other.number)
                              return false;
                      return true;
              }       
      
      }
      
    • =============================================
    • import java.util.HashMap;
      import java.util.Map;
      
      /**
       * Represents an order with an ordernumber (autogenerated), customer, and order lines with products and quantities.
       * 
       * @author kwurst
       * @version Fall 2018
       */
      public class Order {
              
              private static int nextNumber;
              private int number;
              private Customer customer;
              private Map<Product, Integer> lines;
              
              /**
               * Represents an order with an ordernumber (autogenerated), customer, and order lines with products and quantities.
               * @param customer
               */
              public Order(Customer customer) {
                      this.number = nextNumber++;
                      this.customer = customer;
                      this.lines = new HashMap<Product, Integer>();
              }
              
              /**
               * Adds a quantity of a product to the order. If the product is already in the order, increase the order quantity by the quantity.
               * @param product
               * @param quantity must be non-negative
               * @throws IllegalArgumentException if the quantity is negative
               */
              public void addToOrder(Product product, int quantity) {
                      if (quantity < 0) {
                              throw new IllegalArgumentException("Quantity must be non-negative.");
                      }
                      
                      if (lines.containsKey(product)) {
                              lines.put(product, lines.get(product) + quantity);
                      } else {
                              lines.put(product, quantity);
                      }
              }
              
              /**
               * Remove a quantity of a product from the order. If the product is already in the order, decrease the order quantity by the quantity.
               * If the quantity is reduced to zero, remove the product from the order.
               * If the product is in the order, return true. If the product is not in the order, return false.
               * @param product
               * @param quantity must be non-negative
               * @return true if the product was in the order, false otherwise
               */
              public boolean removeFromOrder(Product product, int quantity) {
                      if (quantity < 0) {
                              throw new IllegalArgumentException("Quantity must be non-negative.");
                      }
                      
                      if (lines.containsKey(product)) {
                              if (lines.get(product) <= quantity) {
                                      lines.remove(product);
                              } else {
                                      lines.put(product, lines.get(product) - quantity);
                              }
                              return true;
                      } else {
                              return false;
                      }
              }
              
              /**
               * Determine if a product is in the order
               * @param product to check for
               * @return whether the product is in the order
               */
              public boolean contains(Product product) {
                      return lines.containsKey(product);
              }
              
              /**
               * Determine the quantity of a product in the order
               * @param product to check
               * @return quantity of the product in the order
               */
              public int getItemQuantity(Product product) {
                      if (contains(product)) {
                              return lines.get(product);
                      } else {
                              return 0;
                      }
              }
              
              /**
               * Returns the total cost of the order (unit prices * quantity)
               * @return the total cost of the order (unit prices * quantity)
               */
              public double getOrderTotal() {
                      double total = 0;
                      
                      for (Map.Entry<Product,Integer> entry : lines.entrySet()) {
                          Product key = entry.getKey();
                          Integer value = entry.getValue();
                          total += key.getUnitPrice() * value;
                      }
                      
                      return total;
              }
              
              /**
               * Returns the number of order lines.
               * @return the number of order lines
               */
              public int getOrderLineCount() {
                      return lines.size();
              }
              
              /**
               * Returns the number of items in the order (sum of quantity of all lines)
               * @returnthe number of items in the order (sum of quantity of all lines)
               */
              public int getOrderItemCount() {
                      int total = 0;
                      
                      for (Map.Entry<Product,Integer> entry : lines.entrySet()) {
                          total += entry.getValue();
                      }
                      
                      return total;
              }
      
              @Override
              public String toString() {
                      return "Order [number=" + number + ", customer=" + customer + ", lines=" + lines + "]";
              }
      
              /** 
               * Orders are equal *only* if their order numbers are equal
               * @see java.lang.Object#equals(java.lang.Object)
               */
              @Override
              public boolean equals(Object obj) {
                      if (this == obj)
                              return true;
                      if (obj == null)
                              return false;
                      if (getClass() != obj.getClass())
                              return false;
                      Order other = (Order) obj;
                      if (number != other.number)
                              return false;
                      return true;
              }
              
      }
      
    • =====================================================
    • public class Product {
              
              private String sku;
              private double unitPrice;
              private String description;
              
              /**
               * Represents a Product with a SKU number, unit price, and description.
               * 
               * @param sku
               * @param unitPrice must be non-negative
               * @param description
               */
              public Product(String sku, double unitPrice, String description) {
                      if (unitPrice < 0) {
                              throw new IllegalArgumentException("Unit price must be non-negative.");
                      }
                      this.sku = sku;
                      this.unitPrice = unitPrice;
                      this.description = description;
              }
      
              /**
               * Returns the unit price
               * @return unit price
               */
              public double getUnitPrice() {
                      return unitPrice;
              }
      
              /**
               * Sets the unit price
               * @param unitPrice must be non-negative
               */
              public void setUnitPrice(double unitPrice) {
                      if (unitPrice < 0) {
                              throw new IllegalArgumentException("Unit price must be non-negative.");
                      }
                      this.unitPrice = unitPrice;
              }
      
              /**
               * Returns the description
               * @return the description
               */
              public String getDescription() {
                      return description;
              }
      
              /**
               * Sets the description
               * @param description
               */
              public void setDescription(String description) {
                      this.description = description;
              }
      
              /**
               * Returns the SKU number
               * @return the SKU number
               */
              public String getSku() {
                      return sku;
              }
      
              @Override
              public String toString() {
                      return "Product [sku=" + sku + ", unitPrice=" + unitPrice + ", description=" + description + "]";
              }
      
              /** 
               * Products are equal *only* if their sku numbers are equal
               * @see java.lang.Object#equals(java.lang.Object)
               */
              @Override
              public boolean equals(Object obj) {
                      if (this == obj)
                              return true;
                      if (obj == null)
                              return false;
                      if (getClass() != obj.getClass())
                              return false;
                      Product other = (Product) obj;
                      if (sku == null) {
                              if (other.sku != null)
                                      return false;
                      } else if (!sku.equals(other.sku))
                              return false;
                      return true;
              }       

Solutions

Expert Solution

Hi, Please find the solution and rate the answer. Please note that Junit 5 has not yet released. Latest version is 4.9. I have used 4.9 for this program.

import org.junit.Test;

import java.util.Random;

public class TEst {
    String getRandomString(int size){
        Random random = new Random();
        int rSize = Math.abs(random.nextInt() % size + 1);
        String sample = "abcdefghijklmnopqrstuvwxyz0123456789";
        String retStr="";
        for (int i = 0; i < rSize; i++) {
            retStr += Character.toString(sample.charAt(Math.abs(random.nextInt()) % 36));
        }
        return retStr;
    }
    @Test
    public void testCustomerNoAutoInc(){
        Customer c = new Customer(getRandomString(5),getRandomString(5));
        Customer c1 = new Customer(getRandomString(5),getRandomString(5));
        assert c1.getNumber()==c.getNumber()+1:"Number not auto incrementing";//Text after colon will print if assert fails
    }

    @Test
    public void testOrderIncrement(){
        Customer c = new Customer(getRandomString(5),getRandomString(5));
        Customer c1 = new Customer(getRandomString(5),getRandomString(5));
        Order o = new Order(c);
        Order o1 = new Order(c1);
        //getNumber method is not present in Order class. PLs do required.
//        assert o.getNumber()+1 = o1.getNumber():"Order number not incrementing";
    }
    @Test
    public void testAddAlreadyInOrder(){
        Customer c = new Customer(getRandomString(5),getRandomString(5));
        Order o = new Order(c);
        Product p = new Product("SKU23423", 2342.22, "Washing machine by Apollo");
        o.addToOrder(p,1);
        o.addToOrder(p,1);
        assert o.getItemQuantity(p) == 2 : "Order not being updated";

    }
    @Test
    public void testRemoveLessThanAlreadyInOrder(){
        Customer c = new Customer(getRandomString(5),getRandomString(5));
        Order o = new Order(c);
        Product p = new Product("SKU23423", 2342.22, "Washing machine by Apollo");
        o.addToOrder(p,2);
        o.removeFromOrder(p,1);
        assert o.getItemQuantity(p) == 1 : "Order was not removed";
    }
    @Test
    public void testRemoveMoreThanAlreadyInOrder(){
        Customer c = new Customer(getRandomString(5),getRandomString(5));
        Order o = new Order(c);
        Product p = new Product("SKU23423", 2342.22, "Washing machine by Apollo");
        o.addToOrder(p,2);
        o.removeFromOrder(p,3);
        assert o.getOrderItemCount() == 0 : "Order was not removed";
    }


}

sAll tests are passing. Below is project structure as a maven project.


Related Solutions

You are required to write 4 significant JUnit tests for the Account class outlined below taking...
You are required to write 4 significant JUnit tests for the Account class outlined below taking into account the specifications below. Your code must include 3 negative test cases. Specifications for the Account class: The constructor takes as arguments the name, ID and the initial balance. The withdrawn method allows any specified amount between $20 and $1000 to be withdrawn but the withdrawn amount cannot exceed the current balance. The withdraw method is expected to throw the AmtTooLow exception if...
Write a Junit test method that takes 2 Arrays of type Integer[], and tests whether these...
Write a Junit test method that takes 2 Arrays of type Integer[], and tests whether these 2 Arrays are equal or not, and also if the elements are all even numbers. Describe under what conditions these 2 Arrays would be considered equal.
You are required to write a `Critical Review` of the two In-Situ Tests written below on...
You are required to write a `Critical Review` of the two In-Situ Tests written below on one Single-Sided WORD DOCUMENT (Not more than one page!): A) Flat Dilatometer Test (DMT) B) Field Vane Shear Test Your `Critical Review` should possess two Sub-Titles (a) `Critical Assumptions related to these Tests`, and (b) `Advantages and Disadvantages of both Tests
MUST BE WRITTEN IN ASSEMBLY LANGUAGE ONLY AND MUST COMPILE IN VISUAL STUDIO You will write...
MUST BE WRITTEN IN ASSEMBLY LANGUAGE ONLY AND MUST COMPILE IN VISUAL STUDIO You will write a simple assembly language program that performs a few arithmetic operations. This will require you to establish your programming environment and create the capability to assemble and execute the assembly programs that are part of this course. Your \student ID number is a 7-digit number. Begin by splitting your student ID into two different values. Assign the three most significant digits to a variable...
The following code must be written using matlab and must be using a for-loop. NOTE! Write...
The following code must be written using matlab and must be using a for-loop. NOTE! Write a computer program that assigns random integers for each entry and generates a row vector. Different random integers should be drawn from different intervals for position 1, position 2, position3 and position 4 of the array. After these first 4 positions are drawn. The whole thing should start over where position5 drawn from same interval as positions 1, position6 drawn from same interval as...
The following code must be written using matlab and must be using a for-loop. NOTE! Write...
The following code must be written using matlab and must be using a for-loop. NOTE! Write a computer program that assigns random integers for each entry and generates a row vector. Different random integers should be drawn from different intervals in chunks of 4 , that is chunk1-chunk2-chunk3-chunk4 The parameters for specifying the lintervals by which the random numbers should be drawn should be able to change and be hardcoded in the script, however, be hardcoded in the script.
Problem Scenario: Following is a problem description. For all hypothesis tests, you MUST state the statistical...
Problem Scenario: Following is a problem description. For all hypothesis tests, you MUST state the statistical test you are using and use the P-VALUE METHOD through Microsoft Excel to make your decision. Show all steps, calculations, and work. For confidence intervals there is a specific Excel tool for each interval.  Treat each part of the question as a separate problem -- we use the same data set but are answering different “research questions”. Many parts of cars are mechanically tested to...
All but which of the following tests must be met in order for a retirement plan...
All but which of the following tests must be met in order for a retirement plan to receive favorable tax treatment as a qualified plan? a. Percentage test b. Ratio test c. Participation test d. Average benefit test 14. An accounting firm has 125 employees. All employees are covered by the firm’s defined benefit plan except for 70 junior associates. Has the minimum participation requirement been met for the plan? a. Yes, both parts of the 50/40 test have been...
Must be written in Java: After completing this lab, you should be able to: Write a...
Must be written in Java: After completing this lab, you should be able to: Write a Java class to represent Time. Create default and parameterized constructors. Create accessor and mutator methods. Write a toString method. This project will represent time in hours, minutes, and seconds. Part 1: Create a new Java class named Time that has the following instance fields in the parameterized constructor: hours minutes seconds Create a default constructor that sets the time to that would represent the...
The paper must be written in current APA format. All sources must be of a scholarly...
The paper must be written in current APA format. All sources must be of a scholarly nature; at least 5 references if possible. The paper must have 3 Level 1 headings that correspond to the following case points: 1) How did the corporate culture of Enron contribute to its bankruptcy? 2) In what ways did Enron's bankers, auditors, and attorneys contribute to Enron's demise? 3) What role did the company's Chief Financial Officer play in creating the problems that led...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT