0Pricing
C# Academy · Lesson

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.

Fakes via interfaces; test data builders is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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() + "%");
  }
}

Fake implementation in tests

A fake implements the interface and returns controlled data so assertions are stable.

using System;

public interface IClock { DateTime NowUtc(); }

public sealed class FakeClock : IClock
{
  private readonly DateTime _fixed;
  public FakeClock(DateTime fixedUtc) { _fixed = fixedUtc; }
  public DateTime NowUtc() { return _fixed; }
}

public static class Assert
{
  public static void AreEqual(int expected, int actual)
  {
    if (expected != actual)
      throw new Exception("Expected " + expected + " but got " + actual);
  }
}

public sealed class DiscountService
{
  private readonly IClock _clock;
  public DiscountService(IClock clock) { _clock = clock; }

  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)
  {
    try
    {
      // Black Friday: 2015-11-27
      DiscountService s1 = new DiscountService(new FakeClock(new DateTime(2015, 11, 27, 0, 0, 0, DateTimeKind.Utc)));
      Assert.AreEqual(50, s1.GetDiscountPercent());

      // Normal day
      DiscountService s2 = new DiscountService(new FakeClock(new DateTime(2015, 11, 26, 0, 0, 0, DateTimeKind.Utc)));
      Assert.AreEqual(0, s2.GetDiscountPercent());

      Console.WriteLine("PASS: discount logic with fake clock");
    }
    catch (Exception ex)
    {
      Console.WriteLine("FAIL: " + ex.Message);
    }
  }
}

Observe side effects

A fake can capture calls so the test verifies side effects without real email/sms.

using System;
using System.Collections.Generic;

public interface INotifier { void Send(string message); }

public sealed class OrderService
{
  private readonly INotifier _notifier;
  public OrderService(INotifier notifier) { _notifier = notifier; }

  public void Place(string product, int qty)
  {
    if (qty <= 0) throw new ArgumentOutOfRangeException("qty");
    // ...
    _notifier.Send("Placed: " + product + " x" + qty);
  }
}

public sealed class FakeNotifier : INotifier
{
  public readonly List<string> Messages = new List<string>();
  public void Send(string message) { Messages.Add(message); }
}

public static class Assert
{
  public static void IsTrue(bool condition, string message)
  {
    if (!condition) throw new Exception(message);
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    FakeNotifier fake = new FakeNotifier();
    OrderService svc = new OrderService(fake);

    try
    {
      svc.Place("Book", 2);
      Assert.IsTrue(fake.Messages.Count == 1, "Expected exactly one notification");
      Assert.IsTrue(fake.Messages[0].IndexOf("Book") >= 0, "Message should mention product");
      Console.WriteLine("PASS: observed notification via fake");
    }
    catch (Exception ex)
    {
      Console.WriteLine("FAIL: " + ex.Message);
    }
  }
}

Test data builder

A tiny builder sets defaults and overrides only what a test needs, making setup short and clear.

using System;

public sealed class Order
{
  public string Product;
  public int Quantity;
  public double UnitPrice;

  public double Total() { return Quantity * UnitPrice; }
}

// Minimal builder for tests
public sealed class OrderBuilder
{
  private string _product = "Item";
  private int _qty = 1;
  private double _price = 1.0;

  public OrderBuilder WithProduct(string name) { _product = name; return this; }
  public OrderBuilder WithQty(int qty) { _qty = qty; return this; }
  public OrderBuilder WithPrice(double price) { _price = price; return this; }
  public Order Build()
  {
    Order o = new Order();
    o.Product = _product;
    o.Quantity = _qty;
    o.UnitPrice = _price;
    return o;
  }
}

public static class Assert
{
  public static void AreEqual(double expected, double actual)
  {
    if (Math.Abs(expected - actual) > 0.0001)
      throw new Exception("Expected " + expected + " but got " + actual);
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    try
    {
      // Quick setup with readable intent
      Order o = new OrderBuilder()
        .WithProduct("Pen")
        .WithQty(3)
        .WithPrice(2.5)
        .Build();

      Assert.AreEqual(7.5, o.Total());
      Console.WriteLine("PASS: builder created valid order");
    }
    catch (Exception ex)
    {
      Console.WriteLine("FAIL: " + ex.Message);
    }
  }
}

Practical tips

Tips:

  • Prefer small interfaces to isolate side effects
  • Keep fakes tiny; capture outputs in fields/lists
  • Builders hold sane defaults and fluent setters
  • Tests read like stories: setup → act → assert

Isolation approach

Quick check: What is the simplest way to isolate a dependency in a unit test?

Recap

Recap: Inject interfaces, use fakes to control and observe behavior, and create inputs quickly with a small test data builder.

Frequently asked questions

Is the “Fakes via interfaces; test data builders” lesson free?

Yes — the full text of “Fakes via interfaces; test data builders” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “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. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Fakes via interfaces; test data builders” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. xUnit/MSTest setup, assertions
  2. Fakes via interfaces; test data builders
  3. Debugging failing tests
← Back to C# Academy