Returning different valuse from mock

1 view
Skip to first unread message

Shrihari Devji

unread,
Nov 7, 2009, 2:04:36 AM11/7/09
to Rhino.Mocks
Hi
I want to mock an add method which will be called say 10 times. I know
this can be achieved from Repeat.Times() feature. But my scenario is
in that 10 calls for first 5 calls I want to return the result as 5
and for the next 5 i want to return the result as 10.
Is this behaviour possible to create using Rhino Mock. If yes please
let me know how can I achive?

Thanks in advance
Regards
Shrihari Devji

Patrick Steele

unread,
Nov 7, 2009, 8:31:18 AM11/7/09
to rhino...@googlegroups.com
There's probably an easier way to do this, but this is what popped
into my head on a Saturday morning. I've never used the "Do()" method
before, but I know it exists. Might help you out. It's just a simple
Console application:

interface IFoo
{
int GetData();
}

class Program
{
private delegate int NextNumberDelegate();

static void Main(string[] args)
{
var foo = MockRepository.GenerateStub<IFoo>();

IEnumerable<int> list = new[] {5, 5, 5, 5, 10, 10, 10, 10};
var enumerator = list.GetEnumerator();

NextNumberDelegate d = () =>
{
enumerator.MoveNext();
return enumerator.Current;
};

foo.Stub(f => f.GetData()).Do(d);

for(int i = 0 ; i < 8 ; i++)
{
Console.WriteLine(foo.GetData());
}
}
}

--
Patrick Steele
http://weblogs.asp.net/psteele

Tim Barcz

unread,
Nov 7, 2009, 5:19:32 PM11/7/09
to rhino...@googlegroups.com
Will this not work?

[Fact]
public void ReturnDifferentValuesFromMock()
{
    var mock = MockRepository.GenerateMock<IFoo>();

    mock.Stub(x => x.GetInt()).Repeat.Times(2).Return(1);
    mock.Stub(x => x.GetInt()).Repeat.Times(2).Return(2);

    Console.WriteLine(mock.GetInt());
    Console.WriteLine(mock.GetInt());
    Console.WriteLine(mock.GetInt());
    Console.WriteLine(mock.GetInt());
}

public interface IFoo
{
    int GetInt();
}


outputs:

1
1
2
2

1 passed, 0 failed, 0 skipped, took 0.66 seconds (Ad hoc).
--
Tim Barcz
Microsoft C# MVP
Microsoft ASPInsider
http://timbarcz.devlicio.us
http://www.twitter.com/timbarcz

Reply all
Reply to author
Forward
0 new messages