Allrameest
Allrameest

Reputation: 4492

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?

Upvotes: 12

Views: 2804

Answers (3)

Seraphim
Seraphim

Reputation: 66

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.

Upvotes: 2

Pedro
Pedro

Reputation: 12328

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.

Upvotes: 14

Yann Trevin
Yann Trevin

Reputation: 3823

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

Upvotes: 2

Related Questions