12

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?

Allrameest
  • 4,364
  • 2
  • 34
  • 50

3 Answers3

14

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.

Pedro
  • 12,032
  • 4
  • 32
  • 45
  • 4
    One thing to look out for is that the function signature has to match the original call even if you aren't going to pass it along. Mine ended up looking something like this: `.Stub(m => m.Load(docId)).Do((Func)(arg => GetDocument()));` Notice how the long is just dumped. Otherwise you get an exception. – Uriah Blatherwick Jun 06 '12 at 18:55
2

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.

Seraphim
  • 66
  • 6
2

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());
Yann Trevin
  • 3,823
  • 1
  • 30
  • 32