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?
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();