如何使用 AutoFixture 创建 SortedList<Tkey, TValue>
How to create a SortedList<Tkey, TValue> with AutoFixture
我尝试使用 AutoFixture 创建一个 SortedList<,>
,但它创建了一个空列表:
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)));
它不是通用的(强类型化为 int
和 string
)。我要创建两个不同的 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 });
}
}
此实现只是概念验证。它在各个地方都缺乏适当的错误处理,但它应该演示该方法。它从 context
解析 IDictionary<TKey, TValue>
,并使用返回值(已填充)创建 SortedList<TKey, TValue>
.
的实例
为了使用它,您需要将它告诉 AutoFixture:
var fixture = new Fixture();
fixture.Customizations.Add(new SortedListRelay());
var actual = fixture.Create<SortedList<int, string>>();
Assert.NotEmpty(actual);
此测试通过。
我尝试使用 AutoFixture 创建一个 SortedList<,>
,但它创建了一个空列表:
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)));
它不是通用的(强类型化为 int
和 string
)。我要创建两个不同的 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 });
}
}
此实现只是概念验证。它在各个地方都缺乏适当的错误处理,但它应该演示该方法。它从 context
解析 IDictionary<TKey, TValue>
,并使用返回值(已填充)创建 SortedList<TKey, TValue>
.
为了使用它,您需要将它告诉 AutoFixture:
var fixture = new Fixture();
fixture.Customizations.Add(new SortedListRelay());
var actual = fixture.Create<SortedList<int, string>>();
Assert.NotEmpty(actual);
此测试通过。