Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Mocks with DUnitX Setup and TearDown

Tags:

delphi

I am working through the Coding Delphi book, and am running into trouble with using Delphi Mocks. When I create the Mock using the [Setup] attribute with DUnitX, it appears as though it never get's created. When I create the Mock within the test itself it works correctly. I thought the point of having Setup and TearDown was so that you didn't have to build the same items for each test.

Below is the code for the unit test

unit uDollarToGalleonsConverterTest;

interface

uses
  uDollarToGalleonsConverter,
  Spring.Services.Logging,
  Delphi.Mocks,
  DUnitX.TestFramework;


type

  [TestFixture]
  TDollarToGalleonConverterTest = class
  private
    Expected, Actual: Double;
    Converter: TDollarsToGalleonsConverter;
    Logger: ILogger;
    [Setup]
    procedure Setup;
    [TearDown]
    procedure TearDown;
  public
    [Test]
    procedure TestPointFiveCutsDollarsInHalf;
  end;


implementation

{ TDollarToGalleonConverterTest }

procedure TDollarToGalleonConverterTest.Setup;
begin
  Logger := TMock<ILogger>.Create;
  Converter := TDollarsToGalleonsConverter.Create(Logger);
end;

procedure TDollarToGalleonConverterTest.TearDown;
begin
  Converter.Free;
end;

procedure TDollarToGalleonConverterTest.TestPointFiveCutsDollarsInHalf;
begin
  Expected := 1.0;

  Actual := Converter.ConvertDollarsToGalleons(2, 0.5);

  Assert.AreEqual(Expected, Actual,
    'Converter failed to convert 2 dollars to 1 galleon');
end;

initialization
  TDUnitX.RegisterTestFixture(TDollarToGalleonConverterTest);

end.
like image 236
TheEndIsNear Avatar asked Mar 25 '14 14:03

TheEndIsNear


2 Answers

By default rtti for methods is generated for public and published methods. If you have any private or protected methods the framework will not find these even if they have the attributes.

So your Setup method will never be called.

like image 84
Stefan Glienke Avatar answered Sep 25 '22 07:09

Stefan Glienke


I know this is an old post, but still worth answering.

The problem is that TMock is a record, and you do not have a variable to hold it. Change Logger to TMock and it should work fine.

Edit : Forgot to mention, TMock has an implicit operator that will implement ILogger, so you can still use Logger where an ILogger is needed.

like image 36
Vincent Parrett Avatar answered Sep 26 '22 07:09

Vincent Parrett