加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

data-annotations – 为什么AutoFixture不使用StringLength数据

发布时间:2020-12-15 08:46:18 所属栏目:Java 来源:网络整理
导读:我正在尝试再次升级到 AutoFixture 2,我遇到了对象数据注释的问题.这是一个示例对象: public class Bleh{ [StringLength(255)] public string Foo { get; set; } public string Bar { get; set; }} 我正在尝试创建一个匿名Bleh,但带有注释的属性是空的,而不
我正在尝试再次升级到 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.我是否错过了创建数据注释对象所需的某种自定义或行为?

解决方法

谢谢你报道这个!

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

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

根据msdn上的描述,StringLengthAttribute类:

>指定数据中允许的最大字符长度
领域. [.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 (version 2.7.2 or newer)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读