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?
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)");
}
}