26

I have a class with a private set property that I want to stub out with rhino mocks. When I try to do this, though, it gives me a compile time error saying I can't set a read only property. I'm new to using Rhino Mocks so I must be missing something here...

public Interface IFoo
{
    int Quantity { get; }
}

[TestMethod]
public void SomeTest()
{
    IFoo foo = MockRepository.GenerateStub<IFoo>();
    foo.Quantity = 5;

    //Asserts and such
}
The Matt
  • 6,618
  • 7
  • 44
  • 61
JChristian
  • 4,042
  • 5
  • 29
  • 34

2 Answers2

34

Use:

foo.Stub (f => f.Quantity).Return (5);

See http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx#UsingExpecttosetupproperties

You can also use:

foo.Expect(f => f.Quantity).Return (5);
Pete
  • 11,313
  • 4
  • 43
  • 54
  • 2
    Using the Stub method worked perfect after I realized I was trying to stub the concrete class rather than the interface. Thanks! – JChristian Jan 19 '10 at 00:41
  • I found that `Expect` doesn't work if the property is called multiple time as the second time onwards the original property implementation was called - in this case `Stub` was actually what I wanted. – Justin Jun 27 '12 at 13:05
  • Tried with Rhino 3.6.1 and doesn't work: "You are trying to set an expectation on a property that was defined to use PropertyBehavior"... I hate legacy code – zameb Jul 28 '21 at 13:08
4

You can just do:

foo.Stub(f => f.Quantity).Return(5);
//asserts
Lee
  • 142,018
  • 20
  • 234
  • 287