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?
Here is my solution, and notes.
First, it is clear that there is some tight coupling in AutoFixture.Create to knowledge of how a specimen is built and customized. For strings, it's annoying because we know the default is a Guid. Using this knowledge, I created a Func that handles this in my test cases:
private readonly Func _createString = (IFixture fixture, int length) => (fixture.Create() + fixture.Create()).Substring(0, length);
This could be inductively defined to exploit the guid generated by Auto-Fixture by default. It is 36 characters by default, so:
private readonly Func _createString = (IFixture fixture, int length) =>
{
if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
var sb = new StringBuilder();
const int autoFixtureStringLength = 36;
var i = length;
do
{
sb.Append(fixture.Create());
i -= autoFixtureStringLength;
} while (i > autoFixtureStringLength && i % autoFixtureStringLength > 0);
sb.Append(fixture.Create());
return (sb).ToString().Substring(0, length);
};
Again, the whole premise to this solution is that AutoFixture is already tightly coupled to whatever object creation policy you have. All you are doing is dove-tailing on that.
It would probably be ideal if AutoFixture exposed a "min value" and "max value" extension point to query. This is sort of what functional testing frameworks like QuickCheck do, and then let you 'shrink' the value.