【问题标题】:Can I define implementation of methods on Rhino Mocked objects?我可以在 Rhino 模拟对象上定义方法的实现吗?
【发布时间】:2011-08-22 22:05:59
【问题描述】:

使用 Rhino.Mocks,一旦我模拟了一个界面,我就可以:

  • 为模拟对象上的非 void 方法设置“返回”值
  • 检查调用某些方法的方式和值

但是,是否可以有选择地为模拟对象上的方法定义一个实现?

理想情况下,我想这样做(RhinoImplement 是我希望存在的 Rhino 扩展!):

var messages = new List<IMessage>();

IBus bus = MockRepository.GenerateMock<IBus>();

bus.RhinoImplement(b => b.Send(Arg<IMessage>.Is.Anything), imess => messages.Add(imess));

//now run your test on the Class that uses IBus

//now, I can inspect my local (List<IMessage>)messages collection

更新答案

感谢Patrick在下面的回答,实现上述的正确代码是:

var messages = new List<IMessage>();

IBus bus = MockRepository.GenerateMock<IBus>();

bus
    .Expect(b => b.Send(Arg<IMessage>.Is.Anything))
    .WhenCalled(invocation => messages.Add((IMessage)invocation.Arguments[0]))
    .Repeat.Any() //the repeat part is because that method might be called multiple times

//now run your test on the Class that uses IBus

//now, I can inspect my local (List<IMessage>)messages collection

【问题讨论】:

    标签: c# unit-testing mocking rhino-mocks


    【解决方案1】:

    以下代码使用 Rhino 存根而不是 Mock 工作。存根带有副作用的方法。

        private IGuy DefaultDood()
        {
            var guyStub = MockRepository.GenerateStub<IGuy>();
    
            guyStub.Expect(u => u.DrinkHouseholdProducts(Arg<string>.Is.Anything)).WhenCalled(invocation =>
                {
                    guyStub.JustDrank = ((string)invocation.Arguments.First());
                    guyStub.FeelingWell = false;
                }
            );
    
            return guyStub;
        }
    

    【讨论】:

      【解决方案2】:

      使用“WhenCalled”方法:

      Rhino Mocks - Set a property if a method is called

      【讨论】:

      • 感谢 patrick,这有效,但仅在第一次调用 Send 时。知道为什么吗?期望或WhenCalled 仅在第一次通话时有效吗?再次感谢
      • 别担心,修复它。只需要放一个.Repeat.Any()。干杯!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      相关资源
      最近更新 更多