为什么AutoFixture不能使用StringLength数据注释?

lad*_*dge 3 autofixture data-annotations

我正在尝试再次升级到AutoFixture 2,我遇到了对象上的数据注释问题.这是一个示例对象:

public class Bleh
{
    [StringLength(255)]
    public string Foo { get; set; }
    public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个匿名Bleh,但带有注释的属性将变为空,而不是使用匿名字符串填充.

[Test]
public void GetAll_HasContacts()
{
    var fix = new Fixture();
    var bleh = fix.CreateAnonymous<Bleh>();

    Assert.That(bleh.Bar, Is.Not.Empty);  // pass
    Assert.That(bleh.Foo, Is.Not.Empty);  // fail ?!
}
Run Code Online (Sandbox Code Playgroud)

根据Bonus Bits,StringLength应该从2.4.0开始支持,但即使它不受支持,我也不会期望一个空字符串.我正在使用NuGet的 v2.7.1 .我是否错过了创建数据注释对象所需的某种自定义或行为?

Nik*_*nis 7

谢谢你报道这个!

这种行为是设计的(其原因基本上是属性本身的描述).

通过在数据字段上应用[StringLength(255)],它基本上意味着允许最多包含0个字符.

根据msdn上的描述,StringLengthAttribute类:

当前版本(2.7.1)构建于.NET Framework 3.5之上.从2.4.0开始支持StringLengthAttribute类.

话虽这么说,创建的实例是有效的(只是第二个断言语句不是).

这是一个传递测试,它使用System.ComponentModel.DataAnnotations命名空间中的Validator类验证创建的实例:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using NUnit.Framework;
using Ploeh.AutoFixture;

public class Tests
{
    [Test]
    public void GetAll_HasContacts()
    {
        var fixture = new Fixture();
        var bleh = fixture.CreateAnonymous<Bleh>();

        var context = new ValidationContext(bleh, serviceProvider: null, items: null);

        // A collection to hold each failed validation.
        var results = new List<ValidationResult>();

        // Returns true if the object validates; otherwise, false.
        var succeed = Validator.TryValidateObject(bleh, context, 
            results, validateAllProperties: true);

        Assert.That(succeed, Is.True);  // pass
        Assert.That(results, Is.Empty); // pass
    }

    public class Bleh
    {
        [StringLength(255)]
        public string Foo { get; set; }
        public string Bar { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新1:

虽然创建的实例是有效的,但我相信这可以调整为在范围内选择一个随机数(0 - maximumLength),这样用户就不会得到一个空字符串.

我也为论坛创造了一个讨论在这里.

更新2:

如果您升级到AutoFixture版本2.7.2(或更新版本),原始测试用例现在将通过.

[Test]
public void GetAll_HasContacts()
{
    var fix = new Fixture();
    var bleh = fix.CreateAnonymous<Bleh>();

    Assert.That(bleh.Bar, Is.Not.Empty);  // pass
    Assert.That(bleh.Foo, Is.Not.Empty);  // pass (version 2.7.2 or newer)
}
Run Code Online (Sandbox Code Playgroud)