Search code examples
c#mockingrhino-mocks

Stubbing a property twice with rhino mocks


For some objects I want to create default stubs so that common properties contains values. But in some cases I want to override my default behaviour. My question is, can I somehow overwrite an already stubbed value?

//First I create the default stub with a default value
var foo = MockRepository.GenerateStub<IFoo>();
foo.Stub(x => x.TheValue).Return(1);

//Somewhere else in the code I override the stubbed value
foo.Stub(x => x.TheValue).Return(2);

Assert.AreEqual(2, foo.TheValue); //Fails, since TheValue is 1

Solution

  • Using Expect instead of Stub and GenerateMock instead of GenerateStub will solve this:

    //First I create the default stub with a default value
    var foo = MockRepository.GenerateMock<IFoo>();
    foo.Expect(x => x.TheValue).Return(1);
    
    //Somewhere else in the code I override the stubbed value
    foo.Expect(x => x.TheValue).Return(2);
    
    Assert.AreEqual(1, foo.TheValue);
    Assert.AreEqual(2, foo.TheValue);