fsl
fsl

Reputation: 831

rhino mocks, return value of stub should depend on input

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?

Upvotes: 4

Views: 4152

Answers (1)

Alexander Stepaniuk
Alexander Stepaniuk

Reputation: 6408

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.

Upvotes: 9

Related Questions