Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different instances for each call using rhino mocks

I've got this code:

Expect.Call(factory.CreateOrder())
    .Return(new Order())
    .Repeat.Times(4);

When this is called four times, every time the same instance is returned. I want difference instances to be returned. I would like to be able to do something like:

Expect.Call(factory.CreateOrder())
    .Return(() => new Order())
    .Repeat.Times(4);

Can this be done in some way?

like image 952
Allrameest Avatar asked Jan 28 '11 13:01

Allrameest


3 Answers

Instead of using

.Return(new Order());

Try using

.Do((Func<Order>)delegate() { return new Order(); });

This will call the delegate each time, creating a new object.

like image 98
Pedro Avatar answered Nov 11 '22 11:11

Pedro


Repeat 4 times your expectation by specifying a different return value each time (notice the Repeat.Once())

for (int i = 0; i < 4; i++)
   Expect.Call(factory.CreateOrder()).Repeat.Once().Return(new Order());

UPDATE: I believe the following will work as well:

Expect.Call(factory.CreateOrder())
  .Repeat.Once().Return(new Order())
  .Repeat.Once().Return(new Order())
  .Repeat.Once().Return(new Order())
  .Repeat.Once().Return(new Order());
like image 42
Yann Trevin Avatar answered Nov 11 '22 12:11

Yann Trevin


Patrick Steele suggested this extenstion method:

public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory)
{
    opts.Return(default(T));
    opts.WhenCalled(mi => mi.ReturnValue = factory());
    return opts;
}

See his blog entry for more details.

like image 34
Seraphim Avatar answered Nov 11 '22 13:11

Seraphim