AutoFixture - configure fixture to limit string generation length

后端 未结 7 1139
长情又很酷
长情又很酷 2020-12-13 17:44

When using autofixture Build method for some type, how can I limit the length of the strings generated to fill that objects string properties/fields?

7条回答
  •  [愿得一人]
    2020-12-13 17:57

    If maximum length is a constraint and you own the source code for the type, you can use the StringLengthAttribute class to specify the maximum length of characters that are allowed.

    From version 2.6.0, AutoFixture supports DataAnnotations and it will automatically generate a string with the maximum length specified.

    As an example,

    public class StringLengthValidatedType
    {
        public const int MaximumLength = 3;
    
        [StringLength(MaximumLength)]
        public string Property { get; set; }
    }
    
    [Fact]
    public void CreateAnonymousWithStringLengthValidatedTypeReturnsCorrectResult()
    {
        // Fixture setup
        var fixture = new Fixture();
        // Exercise system
        var result = fixture.CreateAnonymous();
        // Verify outcome
        Assert.True(result.Property.Length <= StringLengthValidatedType.MaximumLength);
        // Teardown
    }
    

    The above test will also pass when using Build (to customize the creation algorithm for a single object):

    var result = fixture.Build().CreateAnonymous();
    

提交回复
热议问题