Test: Assert an Exception
Write and test a validation feature in the ShoppingCart class to prevent the addition of items with negative quantities or prices.
Part 1: Writing the Failing Test
Create the Test for Negative Quantity
In your test project, under
ShoppingCartTests.cs
, write a new test method to ensure that an exception is thrown when attempting to add an item with a negative quantity.
Run the Test
Execute the test. It should fail, indicating that the ShoppingCart class currently does not handle this scenario.
Part 2: Implementing the Validation
Add Validation Logic to ShoppingCart
Modify the
AddItem
method in theShoppingCart
class to include validation logic that checks for negative quantities and prices.
Re-run the Test
Run the test again. It should now pass, confirming that the ShoppingCart class correctly handles negative quantities.
Part 3: Refactoring (Optional)
Refactor if Necessary
Review the code and tests for any possible improvements in readability or efficiency.
Last updated