How can I modify the result of a method call on a mocked object before it is returned?

StackOverflow https://stackoverflow.com/questions/5105533

  •  13-12-2020
  •  | 
  •  

Given the following streamlined example, using RhinoMocks and MSpec:

[Subject(typeof (LocationController))]
public class when_creating_a_location_with_invalid_model : context_for_location_controller
{
    static LocationModel model = new LocationModel();
    static SelectList states = new SelectList(new Dictionary<string,string> {
        { "IN", "Indiana" }, { "NY", "New York" }
    });

    static ActionResult result;

    Establish context = () =>
        {
            LocationModelBuilder.Stub(x =>
                x.Build(Arg<LocationModel>.Is.Equal(model))).Return(model);
        }

    Because of = () => result = subject.Create(model);

    It should_automatically_select_a_state = () => result.Model<LocationModel>()
         .States.ShouldNotBeEmpty();
}

How can I modify the object contained in the model variable before it is returned from the stubbed call of LocationModelBuilder.Build()? I want to perform an assignment like model.States = states just before return on Build(). I tried playing with the Do() handler but I give up...

有帮助吗?

解决方案

Try using WhenCalled(). The parameter to WhenCalled allows access to the mocked method's arguments and you can also set the return value.

.WhenCalled(m => {
   Model model = (Model) m.Arguments[0];
   model.States = ...;
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top