Rhino Mocks接收参数,修改它并返回?

Ale*_*sky 37 .net c# rhino-mocks

我想写这样的东西:

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

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

这种情况是否适用于Rhino Mocks?

Dar*_*rov 94

你可以使用这样的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;
    });
Run Code Online (Sandbox Code Playgroud)

然后你可以这样创建你的存根:

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

  • @samjudson:即使使用IgnoreArguments,Rhino仍会抛出异常而不返回,因此需要返回. (2认同)