Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rhino mocks, return value of stub should depend on input

Tags:

rhino-mocks

I'm looking for a clean way of letting the return value of a stub depend on its input.

At the moment im using the following approach, which doesn't scall well.

metadataLogic.Expect(x => x.GetMake(args.Vehicle1.Make)).Return(new CarMake { Id = args.Vehicle1.Make });
metadataLogic.Expect(x => x.GetMake(args.Vehicle2.Make)).Return(new CarMake { Id = args.Vehicle2.Make });

Any suggestions?

like image 911
fsl Avatar asked Jan 15 '23 02:01

fsl


1 Answers

When Stub return or stub actions should depend on arguments then you could use Do handler few examples on github

Regarding your example.
My assumptions are:
There are some class CarMake and interface IMetadataLogic like the following:

class CarMake
{
    public string Id { get; set; }
}

interface IMetadataLogic
{
    CarMake GetMake(string id);
}

And metadataLogic is

var metadataLogic = MockRepository.GenerateStub<IMetadataLogic>();

If you need to just setup a Stub which returns CarMake instance with specified Id then you could do something like that:

metadataLogic
   .Stub(x => x.GetMake(Arg<string>.Is.Anything))
   .Do((Func<string, CarMake>)(id => new CarMake { Id = id }));

Unfortunately explicit cast lambda expression to delegate is necessary.

Please note stub in my example works for any argument but stub in your example works only for args.Vehicle1.Make and for args.Vehicle2.Make.

P.S.
If you need to just setup Stub you don't need to use Expect() method. You can use Stub() instead.

like image 161
Alexander Stepaniuk Avatar answered Mar 31 '23 23:03

Alexander Stepaniuk