I'm writing a unit test with a mock and I'm having trouble writing it successfully. One of the properties is a collection and I need to reference it when setting an expectation for the mock. Right now the expectation statement throws a null. Here's what it roughly looks like.
IFoo myMock = MockRepository.GenerateMock<IFoo>();
List<Entity> col = new List<Entity>();
Entity entity = new Entity();
myMock.Expect(p => p.FooCollection).Return(col);
myMock.Expect(p => p.FooCollection.Add(entity)); // throws null exception here
I'm new to rhino mocks and have a feeling I'm not doing this correctly. Is there anyway else to properly instantiate the collection? Possibly without an expectation like I have above?
Update
I think I'm having the problem because the interface I defined specifies the collection as readonly.
interface IFoo
{
List<Entity> FooCollection { get; }
}
I'm not overly familiar with Rhino Mocks, but I think your expectations aren't actually hooked up until you call .Replay()
- the mocking methodology you hint at in your example looks more like Moq to me.
That said, I think you're doing something more fundamentally wrong here. Exactly what is it that you want to test? Is it the p
object, or something on List<Entity>
? If what you actually want to test is that p.YourMethodUnderTest()
actually adds entity
to the collection, you probably just want to setup p.FooCollection
to return your list, and then verify that your list contains the entity object.
// Arrange
IFoo myMock = MockRepository.GenerateMock<IFoo>();
List<Entity> col = new List<Entity>();
Entity entity = new Entity();
myMock.Expect(p => p.FooCollection).Return(col);
// myMock.Expect(p => p.FooCollection.Add(entity)) - skip this
// Act
p.YourMethodUnderTest(entity);
// Assert
Assert.IsTrue(col.Contains(entity)); // Or something like that