You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TestInsight.DUnitX中用Guard替代Assert进行测试?

不能直接用Guard替代Assert来满足TestInsight.DUnitX的断言统计需求

Guard(Spring4D)和DUnitX的Assert类设计目的完全不同,这是导致你收到“No assertions were made during the test”提示的核心原因:

  • Assert是测试专用组件:它的所有方法都会被TestInsight.DUnitX追踪,框架通过统计Assert的调用次数来确认测试是否执行了有效验证逻辑。测试通过/失败的判定、断言计数都依赖于Assert类的调用。
  • Guard是参数校验工具:它的作用是在业务代码或工具函数中拦截非法输入,抛出EArgumentException系列异常。测试框架会把Guard抛出的异常判定为测试失败,但不会将其统计为“断言执行”——因为框架只认Assert类的方法调用。

可行的解决方案

1. 各司其职:Guard做输入校验,Assert做结果验证

在测试方法中,用Guard校验测试参数的合法性,用Assert验证业务逻辑的输出结果,这样既利用Guard的参数校验能力,又能让TestInsight正确统计断言:

procedure TestMyFunction.TestValidInput;
var
  input: Integer;
  output: Integer;
begin
  // 用Guard确保测试输入合法
  input := 10;
  Guard.CheckGreaterThan(0, input, '输入必须大于0');

  // 执行被测逻辑
  output := MyFunction(input);

  // 用Assert验证结果,触发框架的断言统计
  Assert.AreEqual(20, output, '输出应为输入的2倍');
end;

2. 封装Guard逻辑适配测试断言

如果想复用Guard的校验规则作为测试断言,可以封装一个适配层,将Guard的异常转化为Assert的失败,让框架识别为断言执行:

unit GuardAssertAdapter;

interface

uses
  Spring, DUnitX.Assert;

procedure GuardAssertEquals(const expected, actual: Integer; const message: string = '');
procedure GuardAssertNotNull(const value: TObject; const message: string = '');

implementation

procedure GuardAssertEquals(const expected, actual: Integer; const message: string = '');
begin
  try
    Guard.CheckEquals(expected, actual, message);
  except
    on E: EArgumentException do
      Assert.Fail(E.Message);
  end;
end;

procedure GuardAssertNotNull(const value: TObject; const message: string = '');
begin
  try
    Guard.CheckNotNull(value, message);
  except
    on E: EArgumentNilException do
      Assert.Fail(E.Message);
  end;
end;

end.

在测试中使用这个封装方法,既能复用Guard的校验逻辑,又能让TestInsight统计到断言:

procedure TestMyFunction.TestOutput;
var
  output: Integer;
begin
  output := MyFunction(5);
  GuardAssertEquals(10, output); // 会被TestInsight统计为断言
end;

内容的提问来源于stack exchange,提问作者Ravaut123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:57:23