Question

I have an IEnumerable<T> collection and I want to mock the First<T>() method call. When I tried doing that I get this:

Previous method 'IEnumerator.MoveNext();' requires a return value or an exception to throw.

I am pasting the code below:

IEnumerable<T> collection = MockRepository
    .GenerateStub<IEnumerable<T>>();
collection
    .Stub(x => x.First<T>())
    .IgnoreArguments()
    .Return(MockRepository.GenerateStub<T>());

But the x.First<T> throws the above exception. How do I solve it? I tried returning an IEnumerator by mocking the GetEnumerator() method call as well. It didn't help either.

Était-ce utile?

La solution

I'm going to assume that T is present because the code is in a generic function.

You can't stub a call to First<T>() because it's a static extension method. It isn't defined in IEnumerable<T>, it's a member of Enumerable.

So, you'll need to stub GetEnumerator() on your IEnumerable<T> stub to return an IEnumerator<T> stub, which returns a stub of the type you want:

IEnumerator<T> enumerator = MockRepository.GenerateStub<IEnumerator<T>>();
enumerator.Stub(x => x.MoveNext()).Return(true);
enumerator.Stub(x => x.Current).Return(MockRepository.GenerateStub<T>());
enumerator.Stub(x => x.MoveNext()).Return(false);

IEnumerable<T> collection = MockRepository.GenerateStub<IEnumerable<T>>();
collection.Stub(x => x.GetEnumerator()).Return(enumerator);

However, I would strongly recommend against attempting to mock IEnumerable. Using a List<> with a single item in it is much easier to code initially and read later, and much less brittle:

List<T> listOfT = new List<T>
{
    MockRepository.GenerateStub<T>()
};

It's a really bad idea to stub/mock collection interface types - use the interface, by all means, but back it in your tests with an actual collection.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top