Shopping Cart – Part 3
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.
1. Create a test that fails
Write a unit test named
removedItemTest asserts that an item gets removed after being sold.
Cart.java, write code to make the test fail.
/** * Function name: remove * @param name * * Inside the function: * 1. nothing */
2. Make the test pass
Write code inside
Store.java to make the test pass.
/** * Function name: remove * @param name * * Inside the function: * 1. loop runs through the size of the ArrayList. * 2. removes the item that matches the name passed in. */
removeIf offers a better way to remove elements. It removes elements that match the "predicate". In other words, elements for which the
removeIf expects a Lambda Expression.
The lambda expression for
- receives each element as a parameter.
- has an arrow that points to code.
- returns a
Important: As you refactor, run the unit test to make sure there aren't bugs.