TheEndIsNear
TheEndIsNear

Reputation: 485

Delphi Mocks with DUnitX Setup and TearDown

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.

Upvotes: 6

Views: 2077

Answers (3)

Vincent Parrett
Vincent Parrett

Reputation: 603

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.

Upvotes: 2

Stefan Glienke
Stefan Glienke

Reputation: 21758

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.

Upvotes: 5

Yeah, there appears to be a mismatch between the book and reality:

Try moving your attributed methods to the public section.

Upvotes: 1

Related Questions