4

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

public class Bleh
{
    [StringLength(255)]
    public string Foo { get; set; }
    public string Bar { get; set; }
}

我正在尝试创建一个 anonymous 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 ?!
}

根据 Bonus Bits,StringLength应该从 2.4.0 开始支持,尽管即使不支持我也不希望出现空字符串。我正在使用来自NuGet的 v2.7.1 。我是否错过了创建数据注释对象所需的某种自定义或行为?

4

1 回答 1

7

感谢您报告此事!

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

通过在数据字段上应用 [StringLength(255)] 基本上意味着它允许有 0 到 255 个字符。

根据msdn上的描述,StringLengthAttribute类:

  • 指定数据字段中允许的最大字符长度。[ .NET 框架 3.5 ]

  • 指定数据字段中允许的最小和最大字符长度。[ .NET 框架 4 ]

当前版本 (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; }
    }
}

更新 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)
}
于 2011-12-21T22:21:28.613 回答