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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With