Rhino mocks, the return value of the stub should depend on the input

I am looking for a clean way so that the return value of the stub depends on its input.

Currently im is using the following approach, which doesnโ€™t look very good.

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?

+4
source share
1 answer

When Stub return actions or stubs should depend on the arguments, you can use the Do handler few examples in github

Regarding your example.
My assumptions:
There are several CarMake and interface IMetadataLogic , as shown below:

 class CarMake { public string Id { get; set; } } interface IMetadataLogic { CarMake GetMake(string id); } 

And metadataLogic is

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

If you just need to install Stub, which returns an instance of CarMake with the specified Id , then you can do something like this:

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

Unfortunately, an explicit lambda expression for the delegate is necessary.

Note that the stub in my example works for any argument, but the stub in your example only works for args.Vehicle1.Make and for args.Vehicle2.Make .

PS
If you just need to install Stub, you do not need to use the Expect() method. You can use Stub() instead.

+9
source

Source: https://habr.com/ru/post/1444591/


All Articles