惩戒收藏与犀牛制品 [英] Mocking collections with Rhino Mocks

查看:159
本文介绍了惩戒收藏与犀牛制品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我想很多人都想做的事,嘲笑的集合。在过去的犀牛我都喜欢的东西做到了这一点:

So this is something I guess many people want to do, mock a collection. In the past with Rhino I have done this with something like:

var col_mock = MockRepository.GenerateMock<ICustomCollection>(); // returns ICustom let's say
List<ICustom> col_real = new List<ICustom>();
col_real.Add(custom_mock1);
col_real.Add(custom_mock2);
col_real.Add(custom_mock3);
col_mock.Stub(x => x.GetEnumerator()).Return(col_real.GetEnumerator());

所以烨这工作得很好,当你的foreach col_mock你的嘲笑(custom_mock1等)的对象了。大!我们通过使用类型列表来实际存储嘲笑对象的负载成功地嘲笑定制集合。

So yup this works fine, when you foreach col_mock you get the mocked (custom_mock1 etc.) objects back. Great! We have successfully mocked a custom collection by using a typed list to actually store a load of mocked objects.

现在的问题是,你只能做一次!你可以只的foreach此集合一次。有谁知道(不创建一个实际的自定义集合...)我如何能实现自定义集合可以重复不止一次的嘲讽?

The problem is, you can only do this once! you can only foreach this collection once. Does anyone know (without creating an actual custom collection...) how I can achieve the mocking of a custom collection which can be iterated more than once?

推荐答案

问题是,普查员只能实例化一次,当你调用返回。然后,它返回相同的实例,这已经在列表结束后的第一个的foreach

The problem is that the enumerator is only instantiated once, when you call Return. Then it returns the same instance which is already at the end of the list after the first foreach.

您需要每次都实例化一个新的枚举时的GetEnumerator 被调用。你可以使用 WhenCalled 这样做。

You need to instantiate a new enumerator each time when GetEnumerator is called. You could use WhenCalled to do so.

返回还是需要的,因为它缺少时,犀牛制品会抱怨。不过不要紧,你传递的参数。

Return is still needed, because Rhino Mocks will complain when it is missing. But it doesn't matter what you pass as argument.

[TestMethod]
public void GetEnumerator()
{
    IList<int> col_mock = MockRepository.GenerateMock<IList<int>>();
    List<int> col_real = new List<int>();
    col_real.Add(1);
    col_real.Add(2);
    col_real.Add(3);
    col_mock
        .Stub(x => x.GetEnumerator())
        // create new enumerator instance for each call
        .WhenCalled(call => call.ReturnValue = col_real.GetEnumerator())
        .Return(null) // is ignored, but needed for Rhinos validation
        .Repeat.Any();

    foreach (int i in col_mock)
    {
    }

    int count = 0;
    foreach (int i in col_mock)
    {
        count++;
    }
    Assert.AreSame(3, count);
}

这篇关于惩戒收藏与犀牛制品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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