开发者

Rhino Mocks: Instantiating Mock property so Expectation can reference it

开发者 https://www.devze.com 2023-03-11 12:56 出处:网络
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 n

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> FooCollectio开发者_开发百科n { 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


Instead of mocks you should use stubs, like:

IFoo myMock = MockRepository.GenerateStub<IFoo>();
myMock.FooCollection = col;

Also, you are setting the expectation on a real object (collection.Add()), which won't really work. You can solve this by making your FooCollection property type of IList instead of a concrete List.

Using concrete collection types as parameters is a code smell anyway (and I suggest using FxCop to teach you such things).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号