Moq First()Last()和GetEnumerator()怪异 [英] Moq First() Last() and GetEnumerator() wierdness
问题描述
我是Moqing,我的路线零件来自
rps = new List
... (3 Route Parts)
I am Moqing my Route Parts from a
rps = new List
... (3 Route Parts)
和Moqing GetEnumerator()
如下所示
route.Setup(ro => ro.GetEnumerator()).Returns(rps.GetEnumerator());
,但是Moq
在以下代码中失败,并且在调用Last()
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())
在即时窗口中查看First()
Last()
,我发现如果多次执行First()
Last()
,则值会更改.好像是MoveNext()
被调用但没有被Reset()
调用,并且Enumerable完全混淆了.有没有人通过Moq
遇到过这种情况并找到了解决方案?
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?
推荐答案
您已经设置了GetEnumerator,以便每次都返回相同的枚举器实例.
You've setup your GetEnumerator so that it returns the same enumerator instance every time.
route.Setup(ro => ro.GetEnumerator()).Returns(rps.GetEnumerator());
这等效于:
var enumerator = rps.GetEnumerator()
route.Setup(ro => ro.GetEnumerator()).Returns(enumerator);
如果您希望在每次调用时都使用一个新的枚举数,则需要传递一个返回lambda表达式:
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());
每次调用GetEnumerator()时都会调用lambda-因此First()
和Last()
应该可以按预期工作.
The lambda will get called every time GetEnumerator() is called - so First()
and Last()
should then work as expected.
这篇关于Moq First()Last()和GetEnumerator()怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!