我有以下课程:

public class Foo
{
    public List<DescriptionInfo> Descriptions { get; set; }
}


public class DescriptionInfo
{
    public int LanguageId { get; set; }
    public string Value { get; set; }
}


我想使用Autofixture创建Foo实例。但是,LanguageId必须来自预定义的列表。因此,我创建了以下定制:

public class LanguageIdSpecimenBuilder : ISpecimenBuilder
{
    private static readonly List<int> LanguageIds = new List<int> {
        1,
        2,
        666,
    };

    public object Create(object request, ISpecimenContext context)
    {
        var info = request as PropertyInfo;
        if (info != null)
        {
            if (info.Name == "LanguageID")
            {
                return LanguageIds.GetRandomElement();
            }
        }
        return new NoSpecimen(request);
    }
}


现在一切都很好:

Fixture fixture = new Fixture();
fixture.Customizations.Add(new LanguageIdSpecimenBuilder());
var foo = fixture.Create<Foo>();


但是,还有另一项要求:一种语言ID不得有重复的条目。我该如何实现?

编辑:
例如,有效的实例是:

Foo1:
 - LanguageId: 1, Value: "english description_ae154c"
 - LanguageId: 2, Value: "zuzulu_510b7g"

Foo2:
 - LanguageId: 1, Value: "english description_87f5de"
 - LanguageId: 666, Value: "chinese_35e450"
 - LanguageId: 2, Value: "zuzulu_fe830d"


无效的实例:

Foo1:
 - LanguageId: 1, Value: "_04dcd6"
 - LanguageId: 1, Value: "_66ccc4"
 - LanguageId: 2, Value: "zuzulu_c05b0f"

最佳答案

首先-让我建议您的POC可以更精确。如果您不允许列表中具有相同LanguageID的描述,则可以按如下方式重新构建POC:

public class Foo
{
    public ISet<DescriptionInfo> Descriptions { get; set; }
}

public class DescriptionInfo
{
    public int LanguageID { get; set; }
    public string Value { get; set; }

    public override bool Equals(object obj)
    {
        var anotherInfo = (DescriptionInfo)obj;
        return anotherInfo.LanguageID == LanguageID;
    }

    public override int GetHashCode()
    {
        return LanguageID;
    }
}


问题消失了:

fixture.Customizations.Add(new TypeRelay(typeof(ISet<DescriptionInfo>),
  typeof(HashSet<DescriptionInfo>)));
fixture.Customizations.Add(new LanguageIdSpecimenBuilder());
var foo = fixture.Create<Foo>();


如果您不能/不想重塑POC,则应将重点放在要正确设置的属性-Descriptions的自定义生成器上。

public object Create(object request, ISpecimenContext context)
{
    var info = request as PropertyInfo;
    if (info != null && info.Name == "Descriptions" && info.DeclaringType == typeof(Foo))
    {
        if (info.Name == "Descriptions")
        {
            return context.Create<List<DescriptionInfo>>()
             .GroupBy(g => g.LanguageId)
             .Select(g => g.First())
             .ToList();
         }
    }
    if (info != null && info.Name == "LanguageId" && info.DeclaringType == typeof(DescriptionInfo))
    {
        return LanguageIds.GetRandomElement();
    }
    return new NoSpecimen(request);
}


最后说明-您的代码段错误-字符串比较区分大小写;因此应该为info.Name == "LanguageId",检查声明属性的类型-不仅仅是属性名称也是一个好主意。

关于c# - 自动修复程序生成没有重复的集合(按ID),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35552110/

10-09 06:14