tags:

views:

105

answers:

1

Let's say I have this class:

public abstract class CustomerCollectionBase : Collection<Customer>{}

One of my classes under test accepts CustomerCollectionBase instance (it will be some subclass). In the method under test, this collection is enumerated via for loop and results are examined and processed. like follows:

for(int i=0;i<_customers.Count; i++){
 //process customer
}

Is it possible to stub this collection with Moq so I could pass stub as a dependency to my class-under-test's constructor?

Thank you.

+2  A: 

Technically, this would be possible, but difficult, since the only overridable members of Collection<T> are protected.

It would be much easier to just pass a concrete collection instead, unless you absolutely must perform some interaction-based testing on the collection itself.

However, if you must do this with Moq, you will first need to add the following using directive to your test code:

using Moq.Protected;

You can now use the Protected() methods to setup the mock to with the appropriate protected virtual methods of CustomerCollectionBase.

See this blog post for more information on how to Mock protected members with Moq.

Mark Seemann