Is there a Spring4D correspondent function to WillReturnDefault

256 Views Asked by At

Delphi-Mocks has a WillReturnDefault method when you don't care about the parameters of a function. I can't figure out how to do that with Spring4D mocking. Grateful for help!

1

There are 1 best solutions below

0
Stefan Glienke On BEST ANSWER

You either use the mock in its default dynamic mode where it allows any call and just returns defaults from its methods or use param matchers - see the following example:

uses
  Spring.Mocking;

type
  {$M+}
  ITest = interface
    function GiveNumber(const s: string): Integer;
  end;

var
  m: Mock<ITest>;
begin
  // mocks are dynamic by default so they let all calls happen and return the default
  Writeln(m.Instance.GiveNumber(''));

  // parameter matcher can be either applied to the When call -
  // here we are using the built-in Args.Any to let any parameter happen
  // the actual values passed to GiveNumber does not matter then
  m.Setup.Returns(42).When(Args.Any).GiveNumber('');
  Writeln(m.Instance.GiveNumber('whatever'));

  // when specifying a specific param matcher you basically add this to the existing behavior
  // when calling the mock checks for any given behavior that matches starting from the
  // most recently defined
  m.Setup.Returns(77).When.GiveNumber(Arg.IsEqual('this'));
  Writeln(m.Instance.GiveNumber('this')); // 77 as we just specified
  Writeln(m.Instance.GiveNumber('something')); // 42 as we specified before for any arguments

  // so you should always start with the broader matcher and then the more specific ones
  // as a broader one would "override" a more specific one as you can see now
  m.Setup.Returns(42).When(Args.Any).GiveNumber('');
  // we get 42 now as the Args.Any matcher was added last and matches the parameter
  Writeln(m.Instance.GiveNumber('this'));

  Readln;
end.