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

  1. 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.

    [Fact]
    public void AddItem_WithNegativeQuantity_ThrowsArgumentException()
    {
        var cart = new ShoppingCart();
        var item = new Item("Apple", -1, 0.75);
    
        Action act = () => cart.AddItem(item);
    
        act.Should().Throw<ArgumentException>().WithMessage("*negative*");
    }
  2. 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

  1. Add Validation Logic to ShoppingCart

    • Modify the AddItem method in the ShoppingCart class to include validation logic that checks for negative quantities and prices.

    public class ShoppingCart
    {
        // ... existing code ...
    
        public void AddItem(Item item)
        {
            if (item.Quantity < 0 || item.Price < 0)
            {
                throw new ArgumentException("Quantity and price must be non-negative.");
            }
            Items.Add(item);
        }
    }
  2. 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)

  1. Refactor if Necessary

    • Review the code and tests for any possible improvements in readability or efficiency.

Last updated