Fakes via interfaces; test data builders
Inject dependencies via interfaces, write simple fakes to observe behavior, and build complex inputs with a tiny test data builder.
Isolation via fakes
Goal: Isolate code under test.
- Depend on interfaces
- Provide fakes in tests
- Use a tiny builder for complex inputs
- Observe calls, not the real world
Inject time via IClock
Hide time behind IClock. Tests will pass a fake clock for predictable results.
using System;
public interface IClock { DateTime NowUtc(); }
public sealed class SystemClock : IClock
{
public DateTime NowUtc() { return DateTime.UtcNow; }
}
public sealed class DiscountService
{
private readonly IClock _clock;
public DiscountService(IClock clock) { _clock = clock; }
// 50% off on Black Friday (Nov 27), else 0
public int GetDiscountPercent()
{
DateTime d = _clock.NowUtc().Date;
if (d.Month == 11 && d.Day == 27) return 50;
return 0;
}
}
public class Program
{
public static void Main(string[] args)
{
DiscountService live = new DiscountService(new SystemClock());
Console.WriteLine("Today's discount: " + live.GetDiscountPercent() + "%");
}
}
All lessons in this course
- xUnit/MSTest setup, assertions
- Fakes via interfaces; test data builders
- Debugging failing tests