问题
I am Moqing my Route Parts from a
rps = new List<IRoutePart>
... (3 Route Parts)
and Moqing GetEnumerator() for my Route as below
route.Setup(ro => ro.GetEnumerator()).Returns(rps.GetEnumerator());
but the Moq fails in the following code with "Sequence contains no elements" on the call to Last()
o.Route.Any(rp => rp.IsNonTowLocation && rp != o.Route.First() && rp != o.Route.Last())
Looking at First() Last() in the immediate windows I find the values change if I execute First() Last() multiple times. Its as if the MoveNext() gets called but not Reset() and the Enumerable it totally confused. Has anyone experienced this with Moq and found a solution?
回答1:
You've setup your GetEnumerator so that it returns the same enumerator instance every time.
route.Setup(ro => ro.GetEnumerator()).Returns(rps.GetEnumerator());
This is equivalent to:
var enumerator = rps.GetEnumerator()
route.Setup(ro => ro.GetEnumerator()).Returns(enumerator);
If you want a new enumerator on every call, then you need to pass Returns a lambda expression:
route.Setup(ro => ro.GetEnumerator()).Returns(() => rps.GetEnumerator());
The lambda will get called every time GetEnumerator() is called - so First()
and Last()
should then work as expected.
来源:https://stackoverflow.com/questions/6701475/moq-first-last-and-getenumerator-wierdness