AutoFixture - configure fixture to limit string generation length

后端 未结 7 1145
长情又很酷
长情又很酷 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:54

    Note: This solution does not really use AutoFixture, but sometimes it's harder to use the package then just to program it yourself.

    Why use AF when it's harder and uglier to use AF, my preferred usage is:

    var fixture = new Fixture();
    fixture.Create(length: 9);
    

    So I created an extension method:

    public static class FixtureExtensions
    {
        public static T Create(this IFixture fixture, int length) where T : IConvertible, IComparable, IEquatable
        {
            if (typeof(T) == typeof(string))
            {
                // there are some length flaws here, but you get the point.
                var value = fixture.Create();
    
                if (value.Length < length)
                    throw new ArgumentOutOfRangeException(nameof(length));
    
                var truncatedValue = value.Substring(0, length);
                return (T)Convert.ChangeType(truncatedValue, typeof(T));
            }
    
            // implement other types here
    
            throw new NotSupportedException("Only supported for strings (for now)");
        }
    }
    

提交回复
热议问题