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
pobject, or something onList<Entity>? If what you actually want to test is thatp.YourMethodUnderTest()actually addsentityto the collection, you probably just want to setupp.FooCollectionto return your list, and then verify that your list contains the entity object.