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

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

我正在尝试创建一个匿名的 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 的说法,从 2.4.0 开始应该支持 StringLength,尽管即使不支持它,我也不希望出现空字符串。我正在使用 NuGet 的 v2.7.1。我是否错过了创建数据注释对象所需的某种自定义或行为?

最佳答案

感谢您报告此事!

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

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

根据msdn上的描述,StringLengthAttribute类:

  • 指定数据中允许的最大字符长度
    field 。 [ .NET Framework 3.5 ]
  • 指定字符的最小和最大长度
    允许在数据字段中。 [ .NET Framework 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) 内选择一个随机数,因此用户永远不会得到空字符串。

    我还在论坛 here 上创建了一个讨论。

    更新 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)
    }
    

    关于data-annotations - 为什么 AutoFixture 不能使用 StringLength 数据注释?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8595498/

    10-17 02:11
    查看更多