Test: Add Cart Item
Let's build a simple Shopping Cart in C# using Test-Driven Development (TDD). We'll use xUnit as the testing framework. Make sure you have the xUnit and its runner installed in your development environment. If not, you can add them via NuGet in your IDE.
Step 1: Set up the Solution
Create a new solution in Visual Studio (or your preferred IDE).
Inside the solution, create two projects:
A class library for the Shopping Cart (e.g.,
ShoppingCartLib
)A xUnit test project (e.g.,
ShoppingCartTests
)
Install the Fluent Assertions package to the test project.
Step 2: Add a Reference
In the test project, add a reference to the Shopping Cart project. This allows your tests to access the classes and methods in the Shopping Cart project.
Step 3: Write the First Test
We'll start by writing a test to add an item to the shopping cart.
In your test project, create a new test class ShoppingCartTests.cs
:
using ShoppingCartLib;
using Xunit;
public class ShoppingCartTests
{
[Fact]
public void AddItemToCart()
{
var cart = new ShoppingCart();
cart.AddItem(new Item("Apple", 1, 0.75));
Assert.Single(cart.Items);
Assert.Equal("Apple", cart.Items[0].Name);
Assert.Equal(0.75, cart.Items[0].Price);
}
}
Step 4: Run the Test
Run the test. It should fail because ShoppingCart
and Item
classes do not exist yet.
Step 5: Implement Minimum Code
Now, let's create the minimum code needed to pass the test. In your Shopping Cart library project, add two new classes ShoppingCart.cs
and Item.cs
.
Item.cs
:
public class Item
{
public string Name { get; }
public int Quantity { get; }
public double Price { get; }
public Item(string name, int quantity, double price)
{
Name = name;
Quantity = quantity;
Price = price;
}
}
ShoppingCart.cs
:
using System.Collections.Generic;
public class ShoppingCart
{
public List<Item> Items { get; } = new List<Item>();
public void AddItem(Item item)
{
Items.Add(item);
}
}
Step 6: Re-run the Test
Run the test again. This time it should pass.
Step 7: Refactor if Necessary
Examine your code for any refactoring opportunities. Ensure it's clean and follows good coding practices.
Last updated