【问题标题】:How can I modify the result of a method call on a mocked object before it is returned?如何在模拟对象返回之前修改方法调用的结果?
【发布时间】:2011-02-24 13:53:51
【问题描述】:

给出以下简化示例,使用 RhinoMocks 和 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();
}

如何在 LocationModelBuilder.Build() 的存根调用返回之前修改 model 变量中包含的对象?我想在返回 Build() 之前执行类似model.States = states 的任务。我尝试使用 Do() 处理程序,但我放弃了...

【问题讨论】:

    标签: rhino-mocks mspec


    【解决方案1】:

    尝试使用WhenCalled()。 WhenCalled 的参数允许访问模拟方法的参数,您还可以设置返回值。

    .WhenCalled(m => {
       Model model = (Model) m.Arguments[0];
       model.States = ...;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2022-12-03
      • 1970-01-01
      相关资源
      最近更新 更多