The following feature suggestion was recently posted in the AutoFixture Issue Tracker board:

"We're using AutoFixture to create random rows of data in our DB. A lot of times though, it creates strings that are too long for the database columns. It would be nice if the .With<string> method had an overload that took in a min/max length. We want the random data, but capped at a limit.

"fixture.Build<MyObject>.With(x = x.MyString, 0, 100);

"As an aside, this is for a project that uses Nhibernate and Fluent Nhibernate, which has these lengths already defined. I would be nice if AutoFixture could automatically pick up on that somehow."

I think such an feature is an excellent idea, but I don't think I will include in AutoFixture. Why not?

So far, I have kept the AutoFixture API pretty clean and very generic, and it is my belief that this is one of the main reasons it is so expressive and flexible. There are no methods that only work on specific types (such as strings), and I am reluctant to introduce them now.

In the last six months, I have identified a lot of specialized usage idioms that I would love to package into a reusable library, but I think that they will pollute the core AutoFixture API, so I'm going to put those in one or more optional 'add-on' libraries.

The ability to define strings that are constrained on length could be one such feature, but rather than wait for a helper library, I will show you have you can implement such a method yourself.

The first thing we need is a method that can create anonymous strings given length constraints. One possible implementation is this ConstrainedStringGenerator class:

public class ConstrainedStringGenerator
{
    private readonly int minimumLength;
    private readonly int maximumLength;
 
    public ConstrainedStringGenerator(int minimumLength, 
        int maximumLength)
    {
        if (maximumLength < 0)
        {
            throw new ArgumentOutOfRangeException("...");
        }
        if (minimumLength > maximumLength)
        {
            throw new ArgumentOutOfRangeException("...");
        }
 
        this.minimumLength = minimumLength;
        this.maximumLength = maximumLength;
    }
 
    public string CreateaAnonymous(string seed)
    {
        var s = string.Empty;
        while (s.Length < this.minimumLength)
        {
            s += GuidStringGenerator.CreateAnonymous(seed);
        }
        if (s.Length > this.maximumLength)
        {
            s = s.Substring(0, this.maximumLength);
        }
        return s;
    }
}

The CreateAnonymous method uses AutoFixture's GuidStringGenerator class to create anonymous strings of the required length. For this implementation I chose a basic algorithm, but I'm sure you can create one that is more sophisticated if you need it.

The next thing we need to do is to implement the desired With method. That can be done with an extension method works on ObjectBuilder<T>:

public static class ObjectBuilderExtension
{
    public static ObjectBuilder<T> With<T>(
        this ObjectBuilder<T> ob,
        Expression<Func<T, string>> propertyPicker,
        int minimumLength,
        int maximumLength)
    {
        var me = (MemberExpression)propertyPicker.Body;
        var name = me.Member.Name;
        var generator =
            new ConstrainedStringGenerator(
                minimumLength, maximumLength);
        var value = generator.CreateaAnonymous(name);
        return ob.With(propertyPicker, value);
    }
}

The method takes the same input as ObjectBuilder<T>'s With method, plus the two integers that constrain the length. Note that the propertyPicker expression has been constrained to deal only with strings.

In this implementation, we use the ConstrainedStringGenerator class to generate the desired value for the property, where after we can use the existing With method to assign the value to the property in question.

This now allows us to write Build statements like the one originally requested:

var mc = fixture.Build<MyClass>()
    .With(x => x.SomeText, 0, 100)
    .CreateAnonymous();

The other part of the request, regarding NHibernate integration, I will leave to the interested reader - mostly because I have never used NHibernate, so I have no clue how to do it. I would, however, love to see a blog post with that addition.

This entire example is now part of the AutoFixture test suite, so if you are interested in looking at it in more detail, you can get it from the AutoFixture source code (available at CodePlex).


Comments

Troy #
I see that you have added a ConstrainedStringGenerator class to AutoFixture now but I haven't found any example of how to use it in its new form. What I'm doing currently is providing an ICustomization implementation for domain data that takes max field lengths into consideration. My first question is, is this the right place to do that? If so, how do I reliably get the ISpecimenContext to pass to the Create method? Right now I am creating a SpecimenContext instance myself but again I'm not sure where I should be getting my ISpecimenBuilder instance to pass to it. The 2 leading candidates right now are the Engine property of a Fixture instance that I pass in the constructor as a ISpecimenBuilder or create a StringGenerator instance. If the StringGenerator is what I should use though what should I pass to it in its constructor? Here is an example in case that isn't clear.

fixture.Customize<NwCategory>
(
x => x
.Without(m => m.CategoryID)
.Without(m => m.ProductSet)
.With(m => m.CategoryName, (String)stringGenerator.Create(new ConstrainedStringRequest(NwCategory.MaxLength_CategoryName), new SpecimenContext(this.SpecimenBuilder)))
);
2012-04-26 14:32 UTC
IIRC the ConstrainedStringGenerator class was added to support the [StringLength] attribute. Does this do what you'd like it to do?

There's also a recent discussion about the subject on Stack Overflow.

Finally, perhaps you'll find this post helpful.

If none of these links answer your question, please feel free to ask again. However, Stack Overflow or the AutoFixture discussion list might be better forums, as they are better targeted at Q&A.

HTH
2012-04-27 18:43 UTC


Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or somewhere else with a permalink. Ping me with the link, and I may respond.

Published

Saturday, 07 November 2009 19:56:05 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!
Published: Saturday, 07 November 2009 19:56:05 UTC