0Pricing
C# Academy · 课时

通过接口创建伪对象与测试数据构建器

通过接口注入依赖,编写简单的伪对象来观察行为,并使用小型测试数据构建器构造复杂输入。

通过接口创建伪对象与测试数据构建器 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

通过伪实现进行隔离

目标:隔离正在测试的代码。

  • 依赖接口
  • 在测试中提供伪实现
  • 使用小型构建器处理复杂输入
  • 观察调用,而不接触真实世界

通过 IClock 注入时间

通过 IClock 隐藏时间。测试会传入伪时钟,以获得可预测的结果。

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

测试中的伪实现

伪实现实现该接口并返回受控数据,使断言保持稳定。

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);
    }
  }
}

观察副作用

伪实现可以捕获调用,这样测试无需发送真实的电子邮件或短信,也能验证副作用。

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);
    }
  }
}

测试数据构建器

小型构建器设置默认值,只覆盖测试所需的内容,从而使准备工作简短而清晰。

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);
    }
  }
}

实用提示

提示:

  • 优先使用小型接口来隔离副作用
  • 让伪实现保持小巧;在字段或列表中捕获输出
  • 构建器保存合理的默认值,并提供流式设置器
  • 让测试读起来像故事:准备 → 执行 → 断言

隔离方法

快速检查:在单元测试中隔离依赖项的最简单方法是什么?

回顾

回顾:注入接口,使用伪实现控制并观察行为,并通过小型测试数据构建器快速创建输入。

常见问题解答

「通过接口创建伪对象与测试数据构建器」课时是免费的吗?

是的 — 「通过接口创建伪对象与测试数据构建器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「通过接口创建伪对象与测试数据构建器」这节课中我会学到什么?

通过接口注入依赖,编写简单的伪对象来观察行为,并使用小型测试数据构建器构造复杂输入。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「通过接口创建伪对象与测试数据构建器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. xUnit/MSTest 设置与断言
  2. 通过接口创建伪对象与测试数据构建器
  3. 调试失败的测试
← 返回 C# Academy