Here is all a qualified programmer is gonna need to study
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
// --- DOMAIN MODELS ---
public record Item(string Name, decimal Price);
public class ShoppingCart
{
private readonly List _items = new();
// Exposing as IReadOnlyCollection prevents external modification of the list
// and demonstrates a "Senior" understanding of encapsulation.
public IReadOnlyCollection Items => _items.AsReadOnly();
public int ItemCount => _items.Count;
public void AddItem(Item item)
{
// Defensive check: A "perfect" solution handles nulls immediately.
ArgumentNullException.ThrowIfNull(item);
_items.Add(item);
}
public void RemoveItem(Item item)
{
// Simple removal logic. In a real-world scenario, you might
// handle cases where the item isn't in the list, but for
// a TDD "fundamentals" test, this is the expected behavior.
_items.Remove(item);
}
public decimal GetTotal()
{
decimal total = 0;
foreach (var item in _items)
{
total += item.Price;
}
return total;
}
}
// --- UNIT TESTS ---
// These tests represent the exact "Red-Green-Refactor" steps an interviewer
// watches for. They are written to be as granular as possible.
public class ShoppingCartTests
{
[Fact]
public void NewCart_ShouldBeEmpty()
{
// Step 1: Prove the initial state is correct.
var cart = new ShoppingCart();
Assert.Equal(0, cart.ItemCount);
Assert.Empty(cart.Items);
}
[Fact]
public void AddItem_ShouldIncreaseCountAndStoreItem()
{
// Step 2: Test the adding behavior.
var cart = new ShoppingCart();
var item = new Item("Unit Test Book", 29.99m);
cart.AddItem(item);
Assert.Equal(1, cart.ItemCount);
Assert.Contains(item, cart.Items);
}
[Fact]
public void AddItem_ShouldThrowException_WhenItemIsNull()
{
// Step 3: Edge case testing (shows attention to detail).
var cart = new ShoppingCart();
Assert.Throws(() => cart.AddItem(null!));
}
[Fact]
public void RemoveItem_ShouldDecreaseCount()
{
// Step 4: Test the removal behavior.
var cart = new ShoppingCart();
var item = new Item("Console", 499.99m);
cart.AddItem(item);
cart.RemoveItem(item);
Assert.Equal(0, cart.ItemCount);
Assert.DoesNotContain(item, cart.Items);
}
[Fact]
public void GetTotal_ShouldCalculateSumOfAllItems()
{
// Step 5: Final logic verification (calculating totals).
var cart = new ShoppingCart();
cart.AddItem(new Item("Item A", 10.00m));
cart.AddItem(new Item("Item B", 15.50m));
var total = cart.GetTotal();
Assert.Equal(25.50m, total);
}
}