我尝试创建一个 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)));
它不是通用的(强类型化为 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 });
}
}
此实现只是概念验证。它在各个地方都缺乏适当的错误处理,但它应该演示该方法。它解决了一个 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/