自动混合生成没有重复的集合(通过ID)

时间:2016-02-22 11:11:03

标签: c# .net testing autofixture

我有以下课程:

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"

2 个答案:

答案 0 :(得分:3)

首先 - 让我建议您的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",同样最好检查声明属性的类型 - 而不仅仅是属性名称。

答案 1 :(得分:2)

由于您希望ID值在单个Foo实例上是唯一的,因此您最好自定义Foo类型本身。

您可能希望让AutoFixture处理Foo的其他部分,但DescriptionInfo值除外。一种方法是创建一个ISpecimenCommand,它可以用作生成值的后处理器:

public class UniqueIDsOnFooCommand : ISpecimenCommand
{
    private static readonly int[] languageIds = new [] { 1, 2, 666, };
    private static readonly Random random = new Random();

    public void Execute(object specimen, ISpecimenContext context)
    {
        var foo = specimen as Foo;
        if (foo == null)
            return;

        foreach (var t in
            foo.Descriptions.Zip(Shuffle(languageIds), Tuple.Create))
        {
            var description = t.Item1;
            var id = t.Item2;
            description.LanguageId = id;
        }            
    }

    private static IEnumerable<T> Shuffle<T>(IReadOnlyCollection<T> source)
    {
        return source.OrderBy(_ => random.Next());
    }
}

此实现使用现成的众所周知的语言ID数组shuffles them,然后使用zips them及其说明。

您可以在自定义中打包此命令,以更改Foo类型的行为:

public class FooCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customizations.Add(
            SpecimenBuilderNodeFactory.CreateTypedNode(
                typeof(Foo),
                new Postprocessor(
                    new MethodInvoker(
                        new ModestConstructorQuery()),
                    new CompositeSpecimenCommand(
                        new AutoPropertiesCommand(),
                        new UniqueIDsOnFooCommand()))));
    }
}

以下测试通过:

[Fact]
public void CreateFoos()
{
    var fixture = new Fixture().Customize(new FooCustomization());
    fixture.Behaviors.Add(new TracingBehavior());

    var foos = fixture.CreateMany<Foo>();

    Assert.True(
        foos.All(f => f
            .Descriptions
            .Select(x => x.LanguageId)
            .Distinct()
            .Count() == f.Descriptions.Count),
        "Languaged IDs should be unique for each foo.");
}

创建的Foo值如下所示:

  Foo:
  - LanguageId: 1, Value: "Valueefd1268c-56e9-491a-a43d-3f385ea0dfd8"
  - LanguageId: 666, Value: "Value461d7130-7bc0-4e71-96a8-432c019567c9"
  - LanguageId: 2, Value: "Valuee2604a80-f113-485c-8276-f19a97bca505"

  Foo:
  - LanguageId: 2, Value: "Value66eee598-1895-4c0d-b3c6-4262711fe394"
  - LanguageId: 666, Value: "Valuef9a58482-13c6-4491-a690-27b243af6404"
  - LanguageId: 1, Value: "Valueeb133071-dad7-4bff-b8ef-61d3505f1641"

  Foo:
  - LanguageId: 1, Value: "Valuea1161dc6-75e5-45a3-9333-f6bca01e882b"
  - LanguageId: 666, Value: "Value31332272-5b61-4d51-8572-172b781e5f6b"
  - LanguageId: 2, Value: "Value83f80569-277d-49b2-86e5-be256075835e"

所有这一切,consider a different design that doesn't involve settable collection properties