Delphi Mocks with DUnitX Setup and TearDown

delphi

Solution

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.

Problem

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. ```

Original source