Search code examples
delphidelphi-xe2delphi-mocks

How to check contents of parameters with Delphi Mocks Framework?


I'm trying to test with Delphi Mocks framework a class that creates simple value objects and passes them to a collaborator. How to check contents of these objects?

General idea of the code is like this:

TData = class
  Code : string;
  Field1 : string;
  Field2 : string;
end;

IReceiver = interface
  procedure Process(aData : TData);
end;

TSUTClass = class
public
  procedure DoSomething(const aCode : string);
  property Receiver : IReceiver;
end;

So when a call to DoSomething is made, TSUTClass should make several instances of TData and pass them one by one to Receiver.Process. I can verify that correct count of calls is made with this setup:

Mock := TMock<IReceiver>;
Mock.Setup.Expect.Exactly('Process', ExpectedCount);

But how to check if values of Field1 and Field2 are correct?


Solution

  • The mock has a WillExecute method where you can pass an anonymous method that will execute when the mock is called. You can evaluate the passed TData objects. Unfortunately after a quick look it seems that you cannot combine the WillExecute with an expected call count.

    With DSharp Mocks which is very similar to Delphi Mocks it would look like this:

    var
      mock: Mock<IReceiver>;
      sut: TSUTClass;
      callCount: Integer;
    begin
      sut := TSUTClass.Create(mock);
    
      callCount := 0;
      mock.Setup.WillExecute(
        function(const args: TArray<TValue>; const ReturnType: TRttiType): TValue
        var
          data: TData;
        begin
          Inc(callCount);
          data := args[0].AsType<TData>;
          case callCount of
            1:
            begin
              CheckEquals('xyz', data.Field1);
              CheckEquals('abc', data.Field2);
            end;
            2: ///...
          end;
    
        end).Exactly(2).WhenCallingWithAnyArguments.Process(nil);
    
      sut.DoSomething('x');
    end;