Specify different return values for multiple identical method calls?

135 views
Skip to first unread message

Kristopher Schultz

unread,
Oct 24, 2012, 7:21:54 PM10/24/12
to mock...@googlegroups.com
I've been pouring over the docs and can't seem to figure out how to do this. I want a stubbed (getter) method to return one value the first time it's called and a different value the second time it's called. Below is an example of what I've tried (simplified for clarity). Note, I really want to stick to the refactoring-safe syntax that expect() provides...

var mock:ITimeSource = nice(ITimeSource);

var date:Date;

stub(mock).getter("now").returns(new Date(20));
date = mock.now; // returns Date with "time" of 20

stub(mock).getter("now").returns(new Date(500));
date = mock.now; // returns Date with "time" of 20, not 500!

Hob Spillane

unread,
Oct 25, 2012, 9:53:49 AM10/25/12
to mock...@googlegroups.com

You could use callsWithInvocation() and return whatever you like from your own method, like so:

expect(mock.now).callsWithInvocation(someFunction);

private var callCount:int = 0;
private function someFunction(inn:Invocation):Date
{
   callCount++;
   switch(callCount)
   {
case 1:
  return new Date(20);
case 2:
  return new Date(500);

Drew Bourne

unread,
Oct 25, 2012, 12:17:46 PM10/25/12
to mock...@googlegroups.com
The best way to return a sequence of values is to provide them to the .returns() call, e.g.: 

    expect(mock.now).returns(new Date(20), new Date(500)); 

Mockolate will return each value in the order defined once each, and then repeat the last value for any extra calls to the method. 

An alternative is to define separate expectations with specific expected invocation counts, e.g.: 

    expect(mock.now).returns(new Date(20)).once();
    expect(mock.now).returns(new Date(500)).twice();
    expect(mock.now).throws(new Error());

HTH, 
Drew
Reply all
Reply to author
Forward
0 new messages