【问题标题】:How to create a SortedList<Tkey, TValue> with AutoFixture如何使用 AutoFixture 创建 SortedList<Tkey, TValue>
【发布时间】:2016-05-13 19:36:44
【问题描述】:

我尝试使用 AutoFixture 创建 SortedList&lt;,&gt;,但它创建了一个空列表:

var list = fixture.Create<SortedList<int, string>>();

我想出了以下生成项目的方法,但有点笨拙:

fixture.Register<SortedList<int, string>>(
  () => new SortedList<int, string>(
    fixture.CreateMany<KeyValuePair<int,string>>().ToDictionary(x => x.Key, x => x.Value)));

它不是通用的(强类型为intstring)。我要创建两个不同的TValue SortedLists

有更好的建议吗?

【问题讨论】:

    标签: c# unit-testing autofixture


    【解决方案1】:

    这看起来像是 AutoFixture 应该具备的开箱即用功能,所以我添加了an issue for that

    不过,在此之前,您可以执行以下操作。

    首先,创建一个ISpecimenBuilder

    public class SortedListRelay : ISpecimenBuilder
    {
        public object Create(object request, ISpecimenContext context)
        {
            var t = request as Type;
            if (t == null ||
                !t.IsGenericType ||
                t.GetGenericTypeDefinition() != typeof(SortedList<,>))
                return new NoSpecimen();
    
            var dictionaryType = typeof(IDictionary<,>)
                .MakeGenericType(t.GetGenericArguments());
            var dict = context.Resolve(dictionaryType);
            return t
                .GetConstructor(new[] { dictionaryType })
                .Invoke(new[] { dict });
        }
    }
    

    这个实现只是一个概念证明。它在各个地方缺乏适当的错误处理,但它应该演示该方法。它从context 解析IDictionary&lt;TKey, TValue&gt;,并使用返回的值(已填充)创建SortedList&lt;TKey, TValue&gt; 的实例。

    为了使用它,您需要告诉 AutoFixture:

    var fixture = new Fixture();
    fixture.Customizations.Add(new SortedListRelay());
    
    var actual = fixture.Create<SortedList<int, string>>();
    
    Assert.NotEmpty(actual);
    

    此测试通过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多