Moq - cannot iterate through a hidden IEnumerable
We have a reasonably complicated interface hierarchy and I'm struggling to get Moq to do what I want it to.
I have an interface IReservation
which extends IRulesReservation
, and hides its enumerator with a new implementation of another type.
public interface IReservation : IRulesReservation
{
new IEnumerator<IRoutePart> GetEnumerator();
}
IRulesReservation
extends IEnumerable
.
public interface IRulesReservation : IEnumerable<IRulesRoutePart>
{
}
The method I'm trying to test takes in an IReservation
, but at various points needs to access the IEnumerable<IRulesRoutePart>
. My Mock is setup like so:
m_mock = new Mock<IReservation>();
m_mock.As<IRulesReservation>().Setup(r => r.GetEnumerator()).Returns(routeParts.Select(rp => (IRules开发者_运维技巧RoutePart)rp).GetEnumerator());
In the example, routeParts
is a list of IRouteParts
that come from Mock<IRouteParts>
objects that are setup with .As<IRulesRoutePart>()
.
Whenever I get to a bit of code in the function I'm testing that uses the enumerator, it steps over the iteration as though the collection was empty.
Am I doing something wrong in my setup? Or is Moq just unable to handle an enumerator that is hidden in this way?
Edit: some strange behaviour I've just noticed when running test code on the mock:
Assert.That((reservation.Object as IRulesReservation).Count() == 8);
Assert.That((reservation.Object as IEnumerable<IRulesRoutePart>).Count() == 8);
The first line will pass, but the second line will fail.
I tried changing the mock to specifically setup an enumerator for IEnumerable<IRulesRoutePart>
, but to no effect:
m_mock.As<IEnumerable<IRulesRoutePart>>().Setup(r => r.GetEnumerator()).Returns(routeParts.Select(rp => (IRulesRoutePart)rp).GetEnumerator());
Does the object that your setup returns actually have data? That's probably your problem.
精彩评论