我可以在Rhino Mocked对象上定义方法的实现吗?

时间:2011-05-11 01:00:10

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

使用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

2 个答案:

答案 0 :(得分:4)

使用“WhenCalled”方法:

Rhino Mocks - Set a property if a method is called

答案 1 :(得分:0)

以下代码使用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;
    }