Java Bootcamp – Workbooks and Challenges
)}

Shopping Cart – Part 5

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

1. Create a test that fails


Write a unit test named invalidRemoveState. Inside the unit test, remove both items. The test expects an IllegalStateException if it calls remove() a third time.

@Test(expected = IllegalStateException.class) <----- public void invalidRemoveState() { }

2. Make the test pass


Throw an IllegalStateException from remove if the cart is empty. Run the test and make sure it passes.

3. Refactor

Can the code be simpler? Not the code, but the unit test can be simpler. Add a clear() method to the Cart class and call clear from invalidRemoveState.

Task 2

1. Create a test that fails


Write a unit test named invalidCheckoutState. Inside the unit test, clear() the cart and call checkout(). The test expects an IllegalStateException.

@Test(expected = IllegalStateException.class) <----- public void invalidCheckoutState() { }

2. Make the test pass


Throw an IllegalStateException from checkout if the cart is empty. Run the test and make sure it passes.

3. Refactor

Can the code be simpler? No.

Good Luck!


Feedback Summary
4.8
38 students
5

92%
4

3%
3

0%
2

0%
1

5%
Written Reviews
There are no written reviews yet.