1
在System.Collections.Generic中有一個非常有用的ImmutableList。但是對於這種類型的Autofixture正在拋出一個異常,因爲它沒有公共構造函數,它的創建類似new List<string>().ToImmutableList()
。如何告訴AutoFixture填充它?如何強制AutoFixture創建ImmutableList
在System.Collections.Generic中有一個非常有用的ImmutableList。但是對於這種類型的Autofixture正在拋出一個異常,因爲它沒有公共構造函數,它的創建類似new List<string>().ToImmutableList()
。如何告訴AutoFixture填充它?如何強制AutoFixture創建ImmutableList
所以感謝@馬克塞曼我現在可以回答我的問題:
public class ImmutableListSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var t = request as Type;
if (t == null)
{
return new NoSpecimen();
}
var typeArguments = t.GetGenericArguments();
if (typeArguments.Length != 1 || typeof(ImmutableList<>) != t.GetGenericTypeDefinition())
{
return new NoSpecimen();
}
dynamic list = context.Resolve(typeof(IList<>).MakeGenericType(typeArguments));
return ImmutableList.ToImmutableList(list);
}
}
與用法:
var fixture = new Fixture();
fixture.Customizations.Add(new ImmutableListSpecimenBuilder());
var result = fixture.Create<ImmutableList<int>>();
喜歡的東西
fixture.Register((List<string> l) => l.ToImmutableList());
應該做到這一點。
字符串的偉大工程!是否有任何方法使它對所有類型都是通用的? – user963935
@ user963935這有點多了,但是你應該可以寫一個像'ListRelay]一樣的'ISpecimenBuilder'(https://github.com/AutoFixture/AutoFixture/blob/master/Src/AutoFixture/Kernel/ListRelay.cs )。 –