unit-testing - 德尔福单元测试: Writing a simple spy for the CUT

标签 unit-testing delphi spy dunit dunitx

我正在寻找一种轻松简洁为 Delphi 下的 DUnitX 测试框架编写 spy 程序的方法。

过去,我使用过非常丑陋的方法来做到这一点:

[TestFixture]
Test = class(TObject)
public
  [test]
  procedure Test1;
end;

TMyClass = class(TObject)
protected
  procedure MyProcedure; virtual;
end;

TMyTestClass = class(TMyClass)
protected
  fMyProcedureCalled : Boolean;
  procedure MyProcedure; override;
end

procedure TMyTestClass.MyProcedure;
begin
   fMyProcedureCalled := true;
   inherited;
end;

procedure Test.Test1;
var aObj : TMyTestClass;
begin
   TMyTestClass.Create;
   Assert.IsTrue(aObj.fMyProcedureCalled);
end;

所有这些代码都用于检查是否调用了过程。太啰嗦了!

有没有办法编写一个 spy 程序来帮助我减少代码?

最佳答案

听起来像是模拟的用例(我在这里使用术语模拟,因为大多数框架将其各种类型的测试 double 称为模拟)

在下面的示例中,我使用 DUnit,但它对 DUnitX 应该没有任何影响。我还使用 Spring4D 1.2 的模拟功能(我没有检查 Delphi Mocks 是否支持此功能)

unit MyClass;

interface

type
  TMyClass = class
  private
    fCounter: Integer;
  protected
    procedure MyProcedure; virtual;
  public
    property Counter: Integer read fCounter;
  end;

implementation

procedure TMyClass.MyProcedure;
begin
  Inc(fCounter);
end;

end.

program Tests;

uses
  TestFramework,
  TestInsight.DUnit,
  Spring.Mocking,
  MyClass in 'MyClass.pas';

type
  TMyClass = class(MyClass.TMyClass)
  public
    // just to make it accessible for the test
    procedure MyProcedure; override;
  end;

  TMyTest = class(TTestCase)
  published
    procedure Test1;
  end;

procedure TMyClass.MyProcedure;
begin
  inherited;
end;

procedure TMyTest.Test1;
var
  // the mock is getting auto initialized on its first use
  // and defaults to TMockBehavior.Dynamic which means it lets all calls happen
  m: Mock<TMyClass>;
  o: TMyClass;
begin
  // set this to true to actually call the "real" method
  m.CallBase := True;
  // do something with o
  o := m;
  o.MyProcedure;

  // check if the expected call actually did happen
  m.Received(Times.Once).MyProcedure;

  // to prove that it actually did call the "real" method
  CheckEquals(1, o.Counter);
end;

begin
  RegisterTest(TMyTest.Suite);
  RunRegisteredTests();
end.

请记住,这仅适用于虚拟方法。

关于unit-testing - 德尔福单元测试: Writing a simple spy for the CUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205850/

相关文章:

javascript - 使用 Sinon Js 测试事件触发后调用的回调

scala - 我们是否需要测试因异常而失败的公共(public)方法的失败场景?

javascript - QUnit : One test per method with multiple assertions or multiple tests per method?

使用Google Mock进行C++高性能单元测试?

string - Delphi:在字符串中执行条件语句

file - 检查.exe文件的文件版本(服务器端),以及是否有较新的下载文件

delphi - 如何编辑 mp3 文件详细信息 (Delphi)

unit-testing - 你如何用 Jasmine 监视 AngularJS 的 $timeout ?

java - 使用 Mockito 在 Java 中模拟谓词

java - 如何模拟返回 `Mono<Void>` 的方法