Refactor code

Since the cart creation is duplicated across all tests, we can do it only once in the constructor of the test class, thereby eliminating repeated code:

using FluentAssertions;
using Moq;

public class ShoppingCartTests
{
    private readonly ShoppingCart _cart;

    //xUnit creates a new instance of the test class for each test, so it is safe to share context!
    public ShoppingCartTests()
    {
        _cart = new ShoppingCart();
    }

    [Fact]
    public void AddItemToCart()
    {      
        _cart.AddItem(new Item("Apple", 1, 0.75));

        _cart.Items.Should().HaveCount(1);
        _cart.Items[0].Name.Should().Be("Apple");
        _cart.Items[0].Price.Should().Be(0.75);
    }

    [Fact]
    public void AddItem_WithNegativeQuantity_ThrowsArgumentException()
    {       
        var item = new Item("Apple", -1, 0.75);

        Action act = () => _cart.AddItem(item);

        act.Should().Throw<ArgumentException>();        
    }

    [Fact]
    public void CalculateTotalCost()
    {       
        _cart.AddItem(new Item("Apple", 2, 0.75));
        _cart.AddItem(new Item("Banana", 3, 0.50)); 

        var total = _cart.CalculateTotalCost();

        total.Should().Be(2 * 0.75 + 3 * 0.50); 
    }
}

Run tests

Run all the tests again to make sure that the refactoring did not have any regressions.

Last updated