Moq First() Last() and GetEnumerator() wierdness

做~自己de王妃 提交于 2019-12-23 07:30:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!