Alex Rivera | Logout

Asserting that a method is called exactly one time

Asked 2008-11-13T02:32:54.140
28

I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.

Here's what I thought would work:

[Test]
public void just_once()
{
    var key = "id_of_something";

    var source = MockRepository.GenerateStub<ISomeDataSource>();
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Once();

    var client = new Client(soure);

    // the first call I expect the client to use the source
    client.GetMeMyThing(key);

    // the second call the result should be cached
    // and source is not used
    client.GetMeMyThing(key);
}

I want this test to fail if the second invocation of GetMeMyThing() calls source.GetSomethingThatTakesALotOfResources().

Edit
Report

1 Answer

2

You can pass a delegate to WhenCalled to count calls:

...
uint callCount = 0;
source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
    .Return(new Something())
    .WhenCalled((y) => { callCount++; });
...
Assert.AreEqual(1, callCount);

Also, you should use a mock not a stub, and verify expectations on the mock too.

answered 2011-03-04T00:59:41.983

Your Answer