lundi 22 février 2016

Autofixture generate collection without duplicates (by ID)

I have following classes:

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


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

I want to create Foo instance, using Autofixture. However, the LanguageId must come from a predefined list. Therefore I've created following customization:

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);
    }
}

Now everything is good:

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

However, there is one more requirement: there must be no duplicated entries for one language ID. How can I achieve this?

Aucun commentaire:

Enregistrer un commentaire