How can I Mock Indexed Property with Rhino Mocks ?
Asked
Active
Viewed 2,826 times
1 Answers
22
I'm assuming you mean a property using this[]
var mockClass = MockRepository.GenerateMock<MockClass>();
mockClass.Expect( m => m["key"] ).Return( "value" ); // return a value
mockClass.Expect( m => m["key2"] = "value2" ); // set a value
... some test in here using something that depends on mockClass...
mockClass.VerifyAllExpectations();

tvanfosson
- 524,688
- 99
- 697
- 795
-
I'm trying this mockClass.Expect(m => m[0]).Return(item); and I get an Index 0 is out of range. Any ideas? – Brian Nov 10 '11 at 18:32
-
@Brian what type is `mockClass`? – tvanfosson Nov 10 '11 at 18:42
-
mockClass is inherited from ConfigurationElementCollection and the error comes public Item this[int index] { get { return base.BaseGet(index) as Item; } set { if (base.BaseGet(index) != null) //Fails Here even though its mocked/stub { base.BaseRemoveAt(index); } this.BaseAdd(index, (ConfigurationElement)value); } } – Brian Nov 10 '11 at 20:55
-
That property isn't virtual so I suspect it may be using the property from the base class. Is it possible to use a wrapper class around ConfigurationElementCollection rather than directly inheriting? Mocking a wrapper is much easier than mocking a class descending from one that is not built with mocking in mind. – tvanfosson Nov 10 '11 at 21:46