Java Bootcamp – Workbooks and Challenges
)}

Shopping Cart – Part 2

Test-Driven Development: write tests before writing code.

Unit testing results in modular code. Modular code is:

  • easy to test.
  • immune to bugs.
  • easy to understand.
  • scalable.

Task 1: @Before

@Before runs a method before each test.

  • Annotate a void method named setup with @Before.
  • Inside setup, set cart equal to a new object of the Cart class.

Task 2

1. Create a test that fails


Inside @Before, add two Item objects:

cart.add(new Item("Pepsi", 1.99)); cart.add(new Item("Crush", 1.99));

Inside Cart.java, create the add method.

/** * Function name: add * @param item * * Inside the function: * 1. adds an Item object */

Inside CartTest.java, write a unit test named itemAddedTest. itemAddedTest asserts that a cart contains() an item after it's added.

Inside Cart.java, write code to make the test fail.

/** * Function name: contains * @param item * @return (boolean) * * Inside the function: * 1. checks if items list contains() item. */

2. Make the test pass


Hint: contains() needs your equals method to compare each item against the parameter. See lesson: The equals() method.

    public boolean equals(Object obj) {
    
        return false if parameter is null.
        
        return false if parameter isn't instance of Item class.

        typecast the object to Item.
        
        compare fields from both objects and return the result.
    }

3. Refactor


Can the code be simpler? No.

Task 3

1. Create a test that fails


Write a unit test named skipsDuplicate. skipsDuplicate asserts that add() returns false for a duplicate item.

Inside Cart.java, write code to make the test fail.

/** * Function name: add * @param item * @return (boolean) <------- * * Inside the function: * 1. adds an Item object * 2. returns true <------- */

2. Make the test pass


/** * Function name: add * @param item * @return (boolean) * * Inside the function: * 1. returns false if item exists. <------- * 1. adds an Item object * 2. returns true if item gets added; <------- */

3. Refactor


Can the code be simpler? No.

Good Luck!


Feedback Summary
4.8
39 students
5

92%
4

3%
3

0%
2

0%
1

5%
Written Reviews
There are no written reviews yet.