T>一个IEnumerable&LT的嘲讽的GetEnumerator()方法;类型 [英] Mocking GetEnumerator() method of an IEnumerable<T> types

查看:96
本文介绍了T>一个IEnumerable&LT的嘲讽的GetEnumerator()方法;类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的测试情况犀牛嘲笑失败:

The following test case fails in rhino mocks:

[TestFixture] 
    public class EnumeratorTest 
    { 
        [Test] 
        public void Should_be_able_to_use_enumerator_more_than_once() 
        { 
            var numbers = MockRepository.GenerateStub<INumbers>(); 
            numbers.Stub(x => x.GetEnumerator()).Return(new List<int> 
{ 1, 2, 3 }.GetEnumerator()); 
            var sut = new ObjectThatUsesEnumerator(); 
            var correctResult = sut.DoSomethingOverEnumerator2Times 
(numbers); 
            Assert.IsTrue(correctResult); 
        } 
    } 
    public class ObjectThatUsesEnumerator 
    { 
        public bool DoSomethingOverEnumerator2Times(INumbers numbers) 
        { 
            int sum1 = numbers.Sum(); // returns 6 
            int sum2 = numbers.Sum(); // returns 0 =[ 
            return sum1 + sum2 == sum1 * 2; 
        } 
    } 
    public interface INumbers : IEnumerable<int> { }



我觉得有一些关于这个测试用例很微妙,我
思考它是从我不是通过犀牛嘲笑存根
实际上是如何工作的思考。通常,当您枚举一个IEnumerable,你
开始用新的IEnumerator。在上面的例子中,它看起来
类似我可以在相同枚举所述第二时间我
呼叫和来重新使用,并且如果枚举是已经在其
基因序列的结尾,这可以解释为什么总和()第二次调用返回0
。如果是这样的话,我怎么可能模拟出的GetEnumerator()在这种
A方式,它表现在,我想要的方式它(例如新
枚举或相同的枚举复位到位置0)?

I think there is something very subtle about this test case, and I think it is from me not thinking through how Rhino Mocks stubbing actually works. Typically, when you enumerate over an IEnumerable, you are starting with a fresh IEnumerator. In the example above, it looks like I could be re-using the same enumerator the second time I am calling sum, and if the enumerator is already at the end of its sequence, that would explain why the second call to Sum() returns 0. If this is the case, how could I mock out the GetEnumerator() in such a way that it behaves in the way that I am wanting it to (e.g. new enumerator or same enumerator reset to position 0)?

你将如何修改上面的测试案例,使第二。总和()调用实际上返回6而不是0?

推荐答案

该WhenCalled()API允许你动态地解决回报。值

The WhenCalled() api lets you dynamically resolve return values.

测试用例更改为以下将允许它通过:

Changing the test case to the following will allow it to pass:

numbers.Stub(x => x.GetEnumerator())
                     .Return(null)
                     .WhenCalled(x => x.ReturnValue = 
                                    new List<int> { 1, 2, 3 }.GetEnumerator()
                                 );



因此,而不是返回相同的枚举,废止的行为都会返回一个新的枚举。

So instead of returning the same enumerator, the stubbed behavior will always return a new enumerator.

这篇关于T&GT;一个IEnumerable&LT的嘲讽的GetEnumerator()方法;类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆