【问题标题】:Rhino Mocks receive argument, modify it and return?Rhino Mocks 接收参数,修改它并返回?
【发布时间】:2011-12-01 15:20:11
【问题描述】:

我正在尝试写这样的东西:

myStub.Stub(_ => _.Create(Arg<Invoice>.It.Anything)).Callback(i => { i.Id = 100; return i; });

我想获取传递给 mock 的实际对象,修改它并返回。

Rhino Mocks 可以实现这种情况吗?

【问题讨论】:

    标签: c# .net rhino-mocks


    【解决方案1】:

    您可以像这样使用WhenCalled 方法:

    myStub
        .Stub(_ => _.Create(Arg<Invoice>.Is.Anything))
        .Return(null) // will be ignored but still the API requires it
        .WhenCalled(_ => 
        {
            var invoice = (Invoice)_.Arguments[0];
            invoice.Id = 100;
            _.ReturnValue = invoice;
        });
    

    然后您可以这样创建存根:

    Invoice invoice = new Invoice { Id = 5 };
    Invoice result = myStub.Create(invoice);
    // at this stage result = invoice and invoice.Id = 100
    

    【讨论】:

    • 我认为可以通过在末尾添加 IgnoreArguments() 来避免调用 Return()。
    • @samjudson:即使使用 IgnoreArguments,Rhino 仍然会在没有 Return 的情况下抛出异常,因此需要 Return。
    【解决方案2】:

    我不需要添加 IgnoreArguments() 来避免使用 Return()。 这是我原来的方法:

    List<myEntity> GetDataByRange(int pageSize, int offsetRecords);
    

    这是我的模拟示例:

    _Repository.Stub(x => x.GetDataByRange(Arg<int>.Is.Anything, Arg<int>.Is.Anything))
               .WhenCalled(x => {
                                  var mylist = entitiesList?.Skip((int)x.Arguments[1])?
                                                      .Take((int)x.Arguments[0])?.ToList();
                                  x.ReturnValue = mylist;   
                                });
    

    【讨论】:

    • 是的,Rhino Mocks 4.0.0+ 似乎不需要在调用.WhenCalled() 之前调用.Return()。但它只适用于方法存根。如果我们存根 Indexer,它仍然需要在 .WhenCalled() 之前使用 .Return()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多