【问题标题】:Why isn't AutoFixture working with the StringLength data annotation?为什么 AutoFixture 不能使用 StringLength 数据注释?
【发布时间】:2011-12-21 19:53:10
【问题描述】:

我再次尝试升级到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,StringLength 自 2.4.0 起应受支持,尽管即使不支持,我也不希望出现空字符串。我正在使用来自NuGet 的 v2.7.1。我是否错过了创建数据注释对象所需的某种自定义或行为?

【问题讨论】:

    标签: data-annotations autofixture


    【解决方案1】:

    感谢您报告此事!

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

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

    根据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; }
        }
    }
    

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

    【讨论】:

    • 感谢您的详细解答。我想(有效的)空字符串给我们带来麻烦的事实表明我们有点滥用 AutoFixture,但我仍然感谢快速更新。我们会尽快试一试!
    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多