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
:
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
:
ShoppingCart.cs
:
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