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.
Installing Fluent API
To install Fluent Assertions in your test project, you can follow these steps:
Using Visual Studio's NuGet Package Manager:
Open your solution in Visual Studio.
Right-click on your test project in the Solution Explorer and select "Manage NuGet Packages."
In the NuGet Package Manager, go to the "Browse" tab and search for "Fluent Assertions."
Find the Fluent Assertions package in the list and click "Install."
Using the .NET Core CLI:
If you prefer using the command line, you can install Fluent Assertions via the .NET Core CLI. Open a command prompt or terminal, navigate to the directory containing your test project, and run the following command:
dotnetaddpackageFluentAssertions
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:
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;
}
}
using System.Collections.Generic;
public class ShoppingCart
{
public List<Item> Items { get; } = new List<Item>();
public void AddItem(Item item)
{
Items.Add(item);
}
}