c# – 如何使用AutoFixture创建SortedList
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 如何使用AutoFixture创建SortedList,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1386字,纯文字阅读大概需要2分钟。
内容图文
![c# – 如何使用AutoFixture创建SortedList](/upload/InfoBanner/zyjiaocheng/819/8149f61bc724428aaf6f454aeccb2fed.jpg)
我尝试创建一个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>从上下文中,并使用返回的值(已填充)来创建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全部内容,希望文章能够帮你解决c# – 如何使用AutoFixture创建SortedList所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。