43

I'm trying to write something like this:

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

I want to get actual object that passed to mock, modify it and return back.

Is this scenario possible with Rhino Mocks?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Alexander Beletsky
  • 19,453
  • 9
  • 63
  • 86

2 Answers2

103

You could use the WhenCalled method like this:

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;
    });

and then you can create your stub as such:

Invoice invoice = new Invoice { Id = 5 };
Invoice result = myStub.Create(invoice);
// at this stage result = invoice and invoice.Id = 100
Guy Daher
  • 5,526
  • 5
  • 42
  • 67
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

I had no need to add IgnoreArguments() to avoid using Return(). This is my original method:

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

Here is my mock example:

_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;   
                            });
AlexMelw
  • 2,406
  • 26
  • 35
mggSoft
  • 992
  • 2
  • 20
  • 35
  • Yeah, it seems that Rhino Mocks 4.0.0+ doesn't require a `.Return()` to be called before `.WhenCalled()` invocation. But it only works for methods stubbing. If we stub an *Indexer* it still require the `.Return()` to be used before `.WhenCalled()`. – AlexMelw Jan 13 '20 at 08:19