Why this post exists
This is Part 3 of Day 4 and the mid-level capstone of my six-day C# deep dive. Part 1 covered extension methods, pattern matching and records. Part 2 covered IDisposable, JSON, unit testing and dependency injection. Along with Day 3 (generics, collections, delegates, events, LINQ and iterators), you now have every mid-level concept. This post puts them all in one real project: an Expense Tracker with a passing test suite.
The post gives you the requirements and a suggested order of work first, then the complete solution, a real session, and the reasons each decision was made. Build it yourself before reading the solution. That is where the learning happens.
Mid-level capstone: Expense Tracker
Now combine everything from Days 3 and 4 in one project. Build an Expense Tracker as a console app. Requirements:
- A generic repository (
IRepository<T>with anIEntityconstraint) - LINQ reports: monthly totals, spending by category for a month, and top spend
- Events for budget alerts (a warning at 80% and an alert when the limit is passed)
- Extension methods (money formatting, weekends, month helpers)
- JSON persistence
- Records for the transactions
- Pattern matching for the categorization rules
- Proper disposal of anything that holds a resource
- At least 10 unit tests
Try it yourself first. A sensible order is: the Expense record and the repository, then the Categorizer with its tests, then reports, then the budget events, then JSON, and the console menu last. Write each test before or right after the code it covers.
Project layout
ExpenseTracker/
ExpenseTracker.Core/ class library: all the logic, no Console calls
Abstractions.cs IEntity, IRepository<T>, InMemoryRepository<T>, IClock
Models.cs Expense, Category, report records, BudgetAlertEventArgs
Extensions.cs ToMoney, IsWeekend, StartOfMonth, InMonth
Categorizer.cs pattern-matching rules
ExpenseService.cs adding expenses, budgets, events
Reports.cs the LINQ reports
ExpenseStore.cs JSON persistence
AuditLog.cs IDisposable audit file
ExpenseTracker.App/ console app: menu and input/output only
Program.cs
ExpenseTracker.Tests/ xUnit test project
ExpenseTrackerTests.cs
dotnet new sln -n ExpenseTracker
dotnet new classlib -n ExpenseTracker.Core
dotnet new console -n ExpenseTracker.App
dotnet new xunit -n ExpenseTracker.Tests
dotnet add ExpenseTracker.App reference ExpenseTracker.Core
dotnet add ExpenseTracker.Tests reference ExpenseTracker.Core
dotnet sln add ExpenseTracker.Core ExpenseTracker.App ExpenseTracker.Tests
Solution
// ===== ExpenseTracker.Core/Abstractions.cs =====
namespace ExpenseTracker.Core;
public interface IEntity
{
int Id { get; }
}
public interface IRepository<T> where T : class, IEntity
{
void Add(T item);
T? Get(int id);
bool Remove(int id);
IReadOnlyList<T> GetAll();
}
public sealed class InMemoryRepository<T> : IRepository<T> where T : class, IEntity
{
private readonly Dictionary<int, T> _items = new();
public void Add(T item)
{
ArgumentNullException.ThrowIfNull(item);
if (!_items.TryAdd(item.Id, item))
{
throw new InvalidOperationException($"A {typeof(T).Name} with id {item.Id} already exists.");
}
}
public T? Get(int id) => _items.GetValueOrDefault(id);
public bool Remove(int id) => _items.Remove(id);
public IReadOnlyList<T> GetAll() => _items.Values.ToList();
}
public interface IClock
{
DateTimeOffset UtcNow { get; }
}
public sealed class SystemClock : IClock
{
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
}
// ===== ExpenseTracker.Core/Models.cs =====
namespace ExpenseTracker.Core;
public enum Category { Food, Transport, Housing, Entertainment, Health, Other }
public enum AlertLevel { Warning, Exceeded }
public sealed record Expense(int Id, DateOnly Date, string Description, decimal Amount, Category Category) : IEntity;
public sealed record MonthTotal(DateOnly Month, decimal Total);
public sealed record CategoryTotal(Category Category, decimal Total, decimal Share);
public sealed class BudgetAlertEventArgs : EventArgs
{
public BudgetAlertEventArgs(Category category, int year, int month, decimal spent, decimal limit, AlertLevel level)
=> (Category, Year, Month, Spent, Limit, Level) = (category, year, month, spent, limit, level);
public Category Category { get; }
public int Year { get; }
public int Month { get; }
public decimal Spent { get; }
public decimal Limit { get; }
public AlertLevel Level { get; }
}
// ===== ExpenseTracker.Core/Extensions.cs =====
using System.Globalization;
namespace ExpenseTracker.Core;
public static class ExpenseExtensions
{
public static string ToMoney(this decimal amount) =>
"$" + amount.ToString("N2", CultureInfo.InvariantCulture);
public static bool IsWeekend(this DateOnly date) =>
date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;
public static DateOnly StartOfMonth(this DateOnly date) => new(date.Year, date.Month, 1);
public static IEnumerable<Expense> InMonth(this IEnumerable<Expense> expenses, int year, int month) =>
expenses.Where(e => e.Date.Year == year && e.Date.Month == month);
}
// ===== ExpenseTracker.Core/Categorizer.cs =====
using System.Text.RegularExpressions;
namespace ExpenseTracker.Core;
public static class Categorizer
{
private static readonly Regex WordPattern = new(@"\p{L}+", RegexOptions.Compiled);
public static Category Categorize(string description, decimal amount)
{
ArgumentException.ThrowIfNullOrWhiteSpace(description);
return (Words(description), amount) switch
{
(_, <= 0) => throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive."),
(var w, _) when Has(w, "grocery", "groceries", "restaurant", "cafe", "coffee", "pizza", "breakfast", "lunch", "dinner") => Category.Food,
(var w, _) when Has(w, "uber", "taxi", "bus", "train", "metro", "fuel", "petrol", "parking") => Category.Transport,
(var w, _) when Has(w, "rent", "mortgage", "electricity", "internet", "water") => Category.Housing,
(var w, _) when Has(w, "movie", "netflix", "spotify", "concert", "game", "games") => Category.Entertainment,
(var w, _) when Has(w, "pharmacy", "doctor", "dentist", "gym", "medicine") => Category.Health,
_ => Category.Other
};
}
// Whole words only: "bus" must not match "business"
private static HashSet<string> Words(string text) =>
WordPattern.Matches(text).Select(m => m.Value.ToLowerInvariant()).ToHashSet();
private static bool Has(HashSet<string> words, params string[] keywords) => keywords.Any(words.Contains);
}
// ===== ExpenseTracker.Core/ExpenseService.cs =====
namespace ExpenseTracker.Core;
public class ExpenseService
{
private readonly IRepository<Expense> _repository;
private readonly Dictionary<Category, decimal> _budgets = new();
private int _nextId;
public ExpenseService(IRepository<Expense> repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_nextId = repository.GetAll().Select(e => e.Id).DefaultIfEmpty(0).Max() + 1;
}
public event EventHandler<Expense>? ExpenseAdded;
public event EventHandler<BudgetAlertEventArgs>? BudgetAlert;
public void SetBudget(Category category, decimal monthlyLimit)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(monthlyLimit);
_budgets[category] = monthlyLimit;
}
public Expense Add(DateOnly date, string description, decimal amount, Category? category = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(description);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
Category resolved = category ?? Categorizer.Categorize(description, amount);
decimal spentBefore = MonthSpend(resolved, date.Year, date.Month);
var expense = new Expense(_nextId++, date, description.Trim(), amount, resolved);
_repository.Add(expense);
ExpenseAdded?.Invoke(this, expense);
CheckBudget(resolved, date, spentBefore, spentBefore + amount);
return expense;
}
private decimal MonthSpend(Category category, int year, int month) =>
_repository.GetAll().Where(e => e.Category == category).InMonth(year, month).Sum(e => e.Amount);
private void CheckBudget(Category category, DateOnly date, decimal before, decimal after)
{
if (!_budgets.TryGetValue(category, out decimal limit)) return;
AlertLevel? level = (before, after) switch
{
var (b, a) when b <= limit && a > limit => AlertLevel.Exceeded, // crossed 100%
var (b, a) when b < limit * 0.8m && a >= limit * 0.8m => AlertLevel.Warning, // crossed 80%
_ => null
};
if (level is { } alertLevel)
{
BudgetAlert?.Invoke(this, new BudgetAlertEventArgs(category, date.Year, date.Month, after, limit, alertLevel));
}
}
}
// ===== ExpenseTracker.Core/Reports.cs =====
namespace ExpenseTracker.Core;
public class ReportService
{
private readonly IRepository<Expense> _repository;
public ReportService(IRepository<Expense> repository) =>
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
public IReadOnlyList<MonthTotal> MonthlyTotals() =>
_repository.GetAll()
.GroupBy(e => e.Date.StartOfMonth())
.OrderBy(g => g.Key)
.Select(g => new MonthTotal(g.Key, g.Sum(e => e.Amount)))
.ToList();
public IReadOnlyList<CategoryTotal> ByCategory(int year, int month)
{
List<Expense> inMonth = _repository.GetAll().InMonth(year, month).ToList();
decimal total = inMonth.Sum(e => e.Amount);
return inMonth
.GroupBy(e => e.Category)
.Select(g => new CategoryTotal(g.Key, g.Sum(e => e.Amount), total == 0 ? 0 : g.Sum(e => e.Amount) / total))
.OrderByDescending(c => c.Total)
.ThenBy(c => c.Category)
.ToList();
}
public IReadOnlyList<Expense> TopSpend(int count) =>
_repository.GetAll()
.OrderByDescending(e => e.Amount)
.ThenBy(e => e.Date)
.ThenBy(e => e.Id)
.Take(count)
.ToList();
public decimal WeekendTotal(int year, int month) =>
_repository.GetAll().InMonth(year, month).Where(e => e.Date.IsWeekend()).Sum(e => e.Amount);
}
// ===== ExpenseTracker.Core/ExpenseStore.cs =====
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ExpenseTracker.Core;
public sealed class DataFileException : Exception
{
public DataFileException(string message, Exception inner) : base(message, inner) { }
}
public static class ExpenseStore
{
private static readonly JsonSerializerOptions Options = new()
{
WriteIndented = true,
Converters = { new JsonStringEnumConverter() }
};
public static void Save(string path, IEnumerable<Expense> expenses)
{
string json = JsonSerializer.Serialize(expenses.OrderBy(e => e.Id).ToList(), Options);
string tempPath = path + ".tmp";
File.WriteAllText(tempPath, json);
File.Move(tempPath, path, overwrite: true); // the old file survives if the write fails halfway
}
public static List<Expense> Load(string path)
{
if (!File.Exists(path)) return new List<Expense>();
try
{
return JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(path), Options) ?? new List<Expense>();
}
catch (JsonException ex)
{
throw new DataFileException($"'{path}' is not a valid expense file.", ex);
}
}
}
// ===== ExpenseTracker.Core/AuditLog.cs =====
namespace ExpenseTracker.Core;
/// <summary>Writes one timestamped line per event. Takes ownership of the writer it is given.</summary>
public sealed class AuditLog : IDisposable
{
private readonly TextWriter _writer;
private readonly IClock _clock;
private bool _disposed;
public AuditLog(TextWriter writer, IClock clock)
{
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
public void OnExpenseAdded(object? sender, Expense e) =>
Write($"ADDED #{e.Id} {e.Description} {e.Amount.ToMoney()} [{e.Category}]");
public void OnBudgetAlert(object? sender, BudgetAlertEventArgs e) =>
Write($"{e.Level.ToString().ToUpperInvariant(),-9}{e.Category}: {e.Spent.ToMoney()} of {e.Limit.ToMoney()}");
private void Write(string message)
{
ObjectDisposedException.ThrowIf(_disposed, this);
_writer.WriteLine($"{_clock.UtcNow:yyyy-MM-dd HH:mm:ss} {message}");
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_writer.Dispose();
}
}
// ===== ExpenseTracker.App/Program.cs =====
using System.Globalization;
using ExpenseTracker.Core;
const string DataFile = "expenses.json";
const string AuditFile = "audit.log";
var repository = new InMemoryRepository<Expense>();
try
{
foreach (Expense expense in ExpenseStore.Load(DataFile)) repository.Add(expense);
}
catch (DataFileException ex)
{
Console.WriteLine($"Cannot start: {ex.Message}");
return;
}
var clock = new SystemClock();
var service = new ExpenseService(repository);
var reports = new ReportService(repository);
using var audit = new AuditLog(new StreamWriter(AuditFile, append: true), clock);
service.ExpenseAdded += audit.OnExpenseAdded;
service.BudgetAlert += audit.OnBudgetAlert;
service.BudgetAlert += ShowAlert;
Console.WriteLine($"Expense tracker ready: {repository.GetAll().Count} expense(s) loaded.");
bool running = true;
while (running)
{
Console.WriteLine();
Console.WriteLine("1) Add 2) List 3) Monthly totals 4) Month by category 5) Top 3 6) Set budget 0) Save and exit");
try
{
switch (Ask("> "))
{
case "1": AddExpense(); break;
case "2": ListExpenses(); break;
case "3": ShowMonthly(); break;
case "4": ShowCategories(); break;
case "5": ShowTop(); break;
case "6": SetBudget(); break;
case "0":
ExpenseStore.Save(DataFile, repository.GetAll());
Console.WriteLine("Saved. Goodbye!");
running = false;
break;
default: Console.WriteLine("Unknown option."); break;
}
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
service.ExpenseAdded -= audit.OnExpenseAdded; // unsubscribe before the log is disposed
service.BudgetAlert -= audit.OnBudgetAlert;
service.BudgetAlert -= ShowAlert;
string Ask(string label)
{
Console.Write(label.EndsWith("> ") ? label : label + ": ");
return Console.ReadLine()?.Trim() ?? "0"; // end of input behaves like "exit"
}
DateOnly ReadDate(string text)
{
if (text.Length == 0) return DateOnly.FromDateTime(clock.UtcNow.UtcDateTime);
if (DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly date)) return date;
throw new ArgumentException("Dates must look like 2026-11-03.");
}
(int Year, int Month) ReadMonth(string text)
{
if (DateOnly.TryParseExact(text + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly d)) return (d.Year, d.Month);
throw new ArgumentException("Months must look like 2026-11.");
}
Category ReadCategory(string text) =>
Enum.TryParse(text, ignoreCase: true, out Category category) && Enum.IsDefined(category)
? category
: throw new ArgumentException($"Category must be one of: {string.Join(", ", Enum.GetNames<Category>())}.");
void AddExpense()
{
string description = Ask("Description");
if (!decimal.TryParse(Ask("Amount"), NumberStyles.Number, CultureInfo.InvariantCulture, out decimal amount))
{
throw new ArgumentException("Amount must be a number.");
}
DateOnly date = ReadDate(Ask("Date yyyy-MM-dd (blank = today)"));
string categoryText = Ask("Category (blank = guess from description)");
Expense added = service.Add(date, description, amount, categoryText.Length == 0 ? null : ReadCategory(categoryText));
Console.WriteLine($"Added #{added.Id}: {added.Description} {added.Amount.ToMoney()} [{added.Category}] on {added.Date:yyyy-MM-dd}");
}
void ListExpenses()
{
foreach (Expense e in repository.GetAll().OrderBy(e => e.Date).ThenBy(e => e.Id))
{
Console.WriteLine($"#{e.Id,-3} {e.Date:yyyy-MM-dd} {e.Amount.ToMoney(),10} {e.Category,-13} {e.Description}");
}
}
void ShowMonthly()
{
foreach (MonthTotal m in reports.MonthlyTotals())
{
Console.WriteLine($"{m.Month:yyyy-MM} {m.Total.ToMoney(),10}");
}
}
void ShowCategories()
{
(int year, int month) = ReadMonth(Ask("Month yyyy-MM"));
foreach (CategoryTotal c in reports.ByCategory(year, month))
{
Console.WriteLine($"{c.Category,-13} {c.Total.ToMoney(),10} {c.Share * 100:F0}%");
}
Console.WriteLine($"Weekend spending: {reports.WeekendTotal(year, month).ToMoney()}");
}
void ShowTop()
{
foreach (Expense e in reports.TopSpend(3))
{
Console.WriteLine($"{e.Amount.ToMoney(),10} {e.Description} ({e.Date:yyyy-MM-dd})");
}
}
void SetBudget()
{
Category category = ReadCategory(Ask("Category"));
if (!decimal.TryParse(Ask("Monthly limit"), NumberStyles.Number, CultureInfo.InvariantCulture, out decimal limit))
{
throw new ArgumentException("Limit must be a number.");
}
service.SetBudget(category, limit);
Console.WriteLine($"Budget for {category} set to {limit.ToMoney()} a month.");
}
static void ShowAlert(object? sender, BudgetAlertEventArgs e) =>
Console.WriteLine($" !! {e.Level}: {e.Category} spending is {e.Spent.ToMoney()} of {e.Limit.ToMoney()} for {e.Month:D2}/{e.Year}");
// ===== ExpenseTracker.Tests/ExpenseTrackerTests.cs =====
using ExpenseTracker.Core;
using Xunit;
namespace ExpenseTracker.Tests;
public class RepositoryTests
{
private readonly InMemoryRepository<Expense> _repository = new();
[Fact]
public void Add_DuplicateId_Throws()
{
_repository.Add(Sample(1));
Assert.Throws<InvalidOperationException>(() => _repository.Add(Sample(1)));
}
[Fact]
public void Get_UnknownId_ReturnsNull() => Assert.Null(_repository.Get(7));
[Fact]
public void Remove_ExistingItem_RemovesIt()
{
_repository.Add(Sample(1));
Assert.True(_repository.Remove(1));
Assert.Empty(_repository.GetAll());
}
private static Expense Sample(int id) => new(id, new DateOnly(2026, 11, 1), "Coffee", 4m, Category.Food);
}
public class CategorizerTests
{
[Theory]
[InlineData("Weekly grocery shopping", Category.Food)]
[InlineData("Uber to the airport", Category.Transport)]
[InlineData("November rent", Category.Housing)]
[InlineData("Netflix subscription", Category.Entertainment)]
[InlineData("Dentist appointment", Category.Health)]
[InlineData("Birthday present", Category.Other)]
public void Categorize_KnownKeywords_ReturnsExpectedCategory(string description, Category expected)
{
Assert.Equal(expected, Categorizer.Categorize(description, 25m));
}
[Fact]
public void Categorize_KeywordInsideAnotherWord_IsIgnored()
{
Assert.Equal(Category.Other, Categorizer.Categorize("Business trip", 120m)); // "bus" is not a whole word here
}
[Fact]
public void Categorize_NonPositiveAmount_Throws()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Categorizer.Categorize("coffee", 0m));
}
}
public class ExtensionTests
{
[Fact]
public void ToMoney_FormatsWithSeparatorsAndTwoDecimals() => Assert.Equal("$1,234.50", 1234.5m.ToMoney());
[Fact]
public void ToMoney_PadsWholeNumbers() => Assert.Equal("$7.00", 7m.ToMoney());
[Theory]
[InlineData("2026-11-07", true)] // Saturday
[InlineData("2026-11-08", true)] // Sunday
[InlineData("2026-11-09", false)] // Monday
public void IsWeekend_ChecksTheDayOfTheWeek(string date, bool expected)
{
Assert.Equal(expected, DateOnly.Parse(date).IsWeekend());
}
}
public class ExpenseServiceTests
{
private static readonly DateOnly Nov = new(2026, 11, 10);
private readonly ExpenseService _service = new(new InMemoryRepository<Expense>());
private readonly List<AlertLevel> _alerts = new();
public ExpenseServiceTests()
{
_service.BudgetAlert += (_, e) => _alerts.Add(e.Level);
}
[Fact]
public void Add_AssignsIncreasingIds()
{
Expense first = _service.Add(Nov, "Coffee", 4m);
Expense second = _service.Add(Nov, "Lunch", 12m);
Assert.Equal(1, first.Id);
Assert.Equal(2, second.Id);
}
[Fact]
public void Add_WithoutCategory_UsesTheCategorizer() =>
Assert.Equal(Category.Transport, _service.Add(Nov, "Train ticket", 30m).Category);
[Fact]
public void Add_WithExplicitCategory_OverridesTheGuess() =>
Assert.Equal(Category.Health, _service.Add(Nov, "Train ticket", 30m, Category.Health).Category);
[Fact]
public void Add_NegativeAmount_Throws() =>
Assert.Throws<ArgumentOutOfRangeException>(() => _service.Add(Nov, "Coffee", -4m));
[Fact]
public void Budget_WarningFiresWhenSpendingReachesEightyPercent()
{
_service.SetBudget(Category.Food, 100m);
_service.Add(Nov, "Dinner", 70m);
Assert.Empty(_alerts);
_service.Add(Nov, "Coffee", 15m);
Assert.Equal(new[] { AlertLevel.Warning }, _alerts);
}
[Fact]
public void Budget_ExceededFiresWhenTheLimitIsPassed()
{
_service.SetBudget(Category.Food, 100m);
_service.Add(Nov, "Dinner", 90m);
_service.Add(Nov, "Lunch", 20m);
Assert.Equal(new[] { AlertLevel.Warning, AlertLevel.Exceeded }, _alerts);
}
[Fact]
public void Budget_DoesNotRepeatAlertsOnceExceeded()
{
_service.SetBudget(Category.Food, 100m);
_service.Add(Nov, "Banquet", 150m, Category.Food);
_service.Add(Nov, "Coffee", 10m);
Assert.Equal(new[] { AlertLevel.Exceeded }, _alerts);
}
[Fact]
public void Budget_IsTrackedPerMonth()
{
_service.SetBudget(Category.Food, 100m);
_service.Add(new DateOnly(2026, 11, 5), "Dinner", 90m);
_service.Add(new DateOnly(2026, 12, 5), "Dinner", 90m);
Assert.Equal(2, _alerts.Count); // December starts from zero again
}
[Fact]
public void NoBudget_NoAlerts()
{
_service.Add(Nov, "Banquet", 5000m);
Assert.Empty(_alerts);
}
}
public class ReportServiceTests
{
private readonly InMemoryRepository<Expense> _repository = new();
private readonly ReportService _reports;
public ReportServiceTests()
{
var service = new ExpenseService(_repository);
service.Add(new DateOnly(2026, 10, 20), "Business trip", 120m); // Tuesday, Other
service.Add(new DateOnly(2026, 11, 1), "November rent", 900m); // Sunday, Housing
service.Add(new DateOnly(2026, 11, 7), "Dinner out", 60m); // Saturday, Food
service.Add(new DateOnly(2026, 11, 9), "Uber to the airport", 40m); // Monday, Transport
_reports = new ReportService(_repository);
}
[Fact]
public void MonthlyTotals_GroupsByMonthInOrder()
{
var totals = _reports.MonthlyTotals();
Assert.Equal(2, totals.Count);
Assert.Equal(new DateOnly(2026, 10, 1), totals[0].Month);
Assert.Equal(120m, totals[0].Total);
Assert.Equal(1000m, totals[1].Total);
}
[Fact]
public void ByCategory_SortsBiggestFirstAndSharesAddUpToOne()
{
var categories = _reports.ByCategory(2026, 11);
Assert.Equal(Category.Housing, categories[0].Category);
Assert.Equal(1m, categories.Sum(c => c.Share), 5);
}
[Fact]
public void TopSpend_ReturnsTheLargestExpensesFirst()
{
var top = _reports.TopSpend(2);
Assert.Equal(new[] { 900m, 120m }, top.Select(e => e.Amount));
}
[Fact]
public void WeekendTotal_CountsOnlySaturdayAndSunday() =>
Assert.Equal(960m, _reports.WeekendTotal(2026, 11));
}
public class ExpenseStoreTests : IDisposable
{
private readonly string _path = Path.Combine(Path.GetTempPath(), $"expenses-{Guid.NewGuid():N}.json");
public void Dispose()
{
if (File.Exists(_path)) File.Delete(_path);
}
[Fact]
public void SaveThenLoad_PreservesEveryExpense()
{
var original = new List<Expense>
{
new(1, new DateOnly(2026, 11, 1), "November rent", 900m, Category.Housing),
new(2, new DateOnly(2026, 11, 7), "Dinner out", 60.5m, Category.Food)
};
ExpenseStore.Save(_path, original);
Assert.Equal(original, ExpenseStore.Load(_path));
}
[Fact]
public void Load_MissingFile_ReturnsEmptyList() => Assert.Empty(ExpenseStore.Load(_path));
[Fact]
public void Load_CorruptFile_ThrowsDataFileException()
{
File.WriteAllText(_path, "{ this is not json");
Assert.Throws<DataFileException>(() => ExpenseStore.Load(_path));
}
}
public class AuditLogTests
{
private readonly StringWriter _output = new();
private readonly AuditLog _log;
public AuditLogTests()
{
_log = new AuditLog(_output, new FixedClock(new DateTimeOffset(2026, 11, 3, 9, 30, 0, TimeSpan.Zero)));
}
[Fact]
public void OnExpenseAdded_WritesATimestampedLine()
{
_log.OnExpenseAdded(this, new Expense(1, new DateOnly(2026, 11, 3), "Coffee", 4.5m, Category.Food));
Assert.Contains("2026-11-03 09:30:00 ADDED #1 Coffee $4.50 [Food]", _output.ToString());
}
[Fact]
public void WritingAfterDispose_Throws()
{
_log.Dispose();
Assert.Throws<ObjectDisposedException>(
() => _log.OnExpenseAdded(this, new Expense(1, new DateOnly(2026, 11, 3), "Coffee", 4m, Category.Food)));
}
[Fact]
public void Dispose_CanBeCalledTwice()
{
_log.Dispose();
_log.Dispose();
}
}
public sealed class FixedClock : IClock
{
public FixedClock(DateTimeOffset now) => UtcNow = now;
public DateTimeOffset UtcNow { get; }
}
The test project has 28 test methods, which expand to 35 test cases once the theories run. They all pass:
Passed! - Failed: 0, Passed: 35, Skipped: 0, Total: 35
A sample session. The menu line is shown once, and the prompts for each Add are condensed to one line. Input is shown after each prompt:
Expense tracker ready: 0 expense(s) loaded.
1) Add 2) List 3) Monthly totals 4) Month by category 5) Top 3 6) Set budget 0) Save and exit
> 6
Category: Food
Monthly limit: 100
Budget for Food set to $100.00 a month.
> 1
Description: Coffee and pizza | Amount: 45 | Date: 2026-11-02 | Category: (blank)
Added #1: Coffee and pizza $45.00 [Food] on 2026-11-02
> 1
Description: Grocery run | Amount: 40 | Date: 2026-11-05 | Category: (blank)
!! Warning: Food spending is $85.00 of $100.00 for 11/2026
Added #2: Grocery run $40.00 [Food] on 2026-11-05
> 1
Description: Dinner out | Amount: 30 | Date: 2026-11-08 | Category: (blank)
!! Exceeded: Food spending is $115.00 of $100.00 for 11/2026
Added #3: Dinner out $30.00 [Food] on 2026-11-08
> 1
Description: Uber to the airport | Amount: 60 | Date: 2026-11-09 | Category: (blank)
Added #4: Uber to the airport $60.00 [Transport] on 2026-11-09
> 1
Description: November rent | Amount: 900 | Date: 2026-11-01 | Category: (blank)
Added #5: November rent $900.00 [Housing] on 2026-11-01
> 1
Description: Business trip | Amount: 120 | Date: 2026-10-20 | Category: (blank)
Added #6: Business trip $120.00 [Other] on 2026-10-20
> 1
Description: Mystery | Amount: abc
Error: Amount must be a number.
> 1
Description: Gift | Amount: 10 | Date: 2026-11-03 | Category: Fun
Error: Category must be one of: Food, Transport, Housing, Entertainment, Health, Other.
> 3
2026-10 $120.00
2026-11 $1,075.00
> 4
Month yyyy-MM: 2026-11
Housing $900.00 84%
Food $115.00 11%
Transport $60.00 6%
Weekend spending: $930.00
> 5
$900.00 November rent (2026-11-01)
$120.00 Business trip (2026-10-20)
$60.00 Uber to the airport (2026-11-09)
> 0
Saved. Goodbye!
Start the app again and the data is back. It also appends to the audit log, and a damaged data file is reported instead of crashing:
Expense tracker ready: 6 expense(s) loaded.
> 2
#6 2026-10-20 $120.00 Other Business trip
#5 2026-11-01 $900.00 Housing November rent
#1 2026-11-02 $45.00 Food Coffee and pizza
#2 2026-11-05 $40.00 Food Grocery run
#3 2026-11-08 $30.00 Food Dinner out
#4 2026-11-09 $60.00 Transport Uber to the airport
(with a corrupt expenses.json)
Cannot start: 'expenses.json' is not a valid expense file.
The audit log (audit.log) from the first food expenses looks like this, one timestamped line per event:
<timestamp> ADDED #1 Coffee and pizza $45.00 [Food]
<timestamp> ADDED #2 Grocery run $40.00 [Food]
<timestamp> WARNING Food: $85.00 of $100.00
<timestamp> ADDED #3 Dinner out $30.00 [Food]
<timestamp> EXCEEDED Food: $115.00 of $100.00
Why this is the best way to write it:
-
All the logic lives in a class library with no
Consolecalls. The app project is only a menu. Every rule is therefore reachable from a test, and the same Core could back a web API tomorrow by writing a new front end. -
The repository is generic and sits behind an interface.
ExpenseServiceandReportServicereceive anIRepository<Expense>in their constructors (Part 2, concept 13). Swapping in a database later changes the wiring, not the logic. -
Expenseis a record. Equality comes free, which is why the persistence test can compare the saved list with the loaded list directly, and it serializes without extra code. -
Categorization is pattern matching on whole words.
Business tripis correctlyOtherbecause the matcher splits text into words and tests membership. AContains("bus")check would wrongly call it Transport, and there is a test that pins this down. - Budget alerts fire when spending crosses a line, not whenever it is above it. The check compares spending before and after the new expense, so adding a 10 to an already-exceeded budget does not spam another alert. Exceeded is tested before Warning, so jumping straight past both gives one alert, not two. Totals are per month, so December starts again from zero.
-
The service publishes events and knows nothing about who listens. The console writes a message and
AuditLogwrites a file, both through+=. The program unsubscribes before the log is disposed, so no event can arrive at a closed file. -
AuditLogtakes aTextWriterand anIClock. In production that is a file and the system clock. In the tests it is aStringWriterand a fixed clock, so the test can assert on the exact text, including the timestamp. It is disposed withusing, flushes on exit, is safe to dispose twice and refuses use after disposal. -
JSON persistence is atomic and tolerant. The file is written to a temp path and moved into place, so a crash mid-save cannot destroy the previous data. A missing file means an empty list. A corrupt file becomes a clear
DataFileExceptionthat the app reports at start-up. -
Reports are one LINQ query each, following the same
GroupBy,Select,OrderByshape from Day 3, withThenByfor stable ties and month keys that are real dates, so they sort correctly. - The tests cover the rules that could silently break: the 80% and 100% thresholds, no repeat alerts, per-month tracking, no alert without a budget, the whole-word match, share totals, ordering and the failure modes of the store. Breaking the 80% rule on purpose made three of them fail, which is the point of having them.
Where each concept appears
- Day 3 generics and constraints:
IRepository<T>andInMemoryRepository<T>withwhere T : class, IEntity - Day 3 collections:
Dictionaryinside the repository and the budgets,HashSetfor the word matching - Day 3 delegates and events:
BudgetAlertandExpenseAddedwithEventHandler<T>, and the console'sShowAlert - Day 3 LINQ: every method in
ReportService, plus the budget total inExpenseService - Extension methods:
ToMoney,IsWeekend,StartOfMonth,InMonth - Pattern matching:
Categorizer(tuple and relational patterns) and the alert-level switch inExpenseService - Records and immutability:
Expense,MonthTotal,CategoryTotal - IDisposable and
using:AuditLogand theusing varinProgram.cs - JSON:
ExpenseStore, with an enum converter andDateOnlysupport - Testing and DI: the
Coreclasses take interfaces, and the test suite usesFixedClock,StringWriterand a temp file
Stretch goals (optional): persist the budgets, add a --month filter to the list command, add a recurring-expense feature using an ITimer-style interface, or expose the same Core as a Minimal API. The Core project would not change at all.
Five things that go wrong in a project like this
Each one follows the same pattern: what people write, why it hurts, what to write instead.
-
Putting
Consolecalls inside the logic. IfExpenseServiceprinted its own alerts, no test could check them. Keep logic in a library that raises events and returns values, and let the app project do the printing. -
Alerting on every expense above the limit. A check like
spent > limitfires again for every coffee after the budget is blown. Compare spending before and after the new expense and alert only when it crosses the line. -
Matching substrings instead of words.
description.Contains("bus")calls "Business trip" public transport. Split the text into whole words and test membership. -
Leaving the audit log subscribed after it is disposed. An event that arrives at a closed writer throws from inside
Add. Unsubscribe before disposing, and make the disposed object fail with a clearObjectDisposedException. - Saving straight over the data file. A crash halfway through leaves a truncated file and loses everything. Write a temp file and move it into place, so the last good copy survives.
Key lessons
- Keep every rule in a library with no
Consolecalls, so each one is reachable from a test - Depend on interfaces (
IRepository<T>,IClock) and create the concrete types in one place - Raise events when a threshold is crossed, and compare before and after
- Categorize with whole-word pattern matching, and pin the tricky cases down with tests
- Give a disposable class its dependencies (a
TextWriterand anIClock) so a test can use aStringWriterand a fixed clock - Save atomically, load tolerantly, and turn a corrupt file into a clear error
- Break a rule on purpose now and then: if no test fails, the tests are not protecting it
Summary
The Expense Tracker is small, but it is built the way real applications are: logic in a library, behaviour behind interfaces, changes announced through events, data persisted safely, and every rule backed by a test. 35 passing test cases are the proof that the pieces work together. That completes the mid-level material. Day 5 starts the advanced half of the plan with async and await, cancellation, threading primitives, concurrent collections, channels and the pitfalls that catch even experienced developers. If you missed the earlier parts, start with Part 1 and Part 2.
More on these topics: C# posts
Top comments (0)