tags:

views:

150

answers:

3

I have something that looks like the following:

var someList = MockRepository.GenerateStub<IList<ISomething>>();
someList.Add(MockRepository.GenerateStub<ISomething>());

The list gets created as a proxy correctly. However, whenever I try to add an item to the list, it doesn't add the item to the list.

I have a feeling this is because the proxy class has no implementation of Add, but I'm wondering how I would remedy this situation without just doing this instead:

var someList = new List<ISomething>();
someList.Add(MockRepository.GenerateStub<ISomething>());

Why would I want to do this? Let's say I have my own special kind of list, say MySpecialList, which is an IList, but in my unit test I don't want to go through the hassle of instanting it, I'd rather just stub it's Add behavior.

+2  A: 

If you actually want the list to behave as a list, why are you stubbing it anyway? Is it just a list of stubs you are after? In which case instantiate a concrete list and add a stubbed ISomething to it.

David M
In my actual test I'm not stubbing it, I'm just creating a List object, as I have on the bottom of my question, but I have had situations where I create my own kind of list and I was wondering in this case how that would be handled. I will edit my question to clarify.
Joseph
+2  A: 

You probably don't really need to have the items added do you? Can't you just set expectations on the number of times that Add() is called and then have something like Count() return the value expected?

Basically you're mocking a List which, I assume, means you're testing a class that depends on the behavior and not the implementation of the list.

Expect.Call(() => someList.Add(1));
Expect.Call(() => someList.Add(2));
Expect.Call(() => someList.Add(3));
Expect.Call(someList.Count()).Returns(3);

methodBeingTested.Call(someList);

mocks.VerifyAll();

That tests that 'methodBeingTested' adds three values and then calls Count() on the list it added the items to.

geofflane
A: 

I believe the GenerateStub method doesn't give you a "smart" stub as you are expecting here, just a mock object which has properties working correctly and is not throwing exceptions when the call is not expected. No magic here.

I use the standard collections as you did, kind of assuming that they are perfectly implemented :)

Grzenio