c# - 如何使用 AutoFixture 创建 SortedList<Tkey, TValue>

标签 c# unit-testing autofixture

我尝试创建一个 SortedList<,>使用 AutoFixture,但它会创建一个空列表:

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创造。

有更好的建议吗?

最佳答案

这看起来像是 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 });
    }
}

此实现只是概念验证。它在各个地方都缺乏适当的错误处理,但它应该演示该方法。它解决了一个 IDictionary<TKey, TValue>来自 context , 并使用返回值(已填充)创建 SortedList<TKey, TValue> 的实例.

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

var fixture = new Fixture();
fixture.Customizations.Add(new SortedListRelay());

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

Assert.NotEmpty(actual);

这个测试通过了。

关于c# - 如何使用 AutoFixture 创建 SortedList<Tkey, TValue>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218084/

相关文章:

c# - 使用 Async 和 Await 中断数据库调用(使用 Dapper)

java - 如何从字符串反序列化请求多部分正文

java - powermock 中意外的方法调用异常

c# - Autofixture 测试接口(interface)类型参数的保护条件

c# - 将 AutoFixture 与具有许多构造函数的类一起使用

c# - 数据网格到 Excel?

c# - 避免两次 WPF 打开同一个窗口

c# - 为集合 UWP 中的每个项目生成一个组

javascript - 使用 angular 2 添加 firebase 的单元测试

c# - 如何添加使用 Autofixture 创建的 Mock 的特定实现?