The default behavior of AutoFixture is to create an Anonymous Variable by assigning a value to all writable properties of the created instance. This is great in many scenarios, but not so much in others. You can disable this behavior by using the OmitAutoProperties method, but sometimes, you would like most of the writable properties set, except one or two.

Consider this simple Person class:

public class Person
{
    private Person spouse;
 
    public DateTime BirthDay { get; set; }
 
    public string Name { get; set; }
 
    public Person Spouse 
    {
        get { return this.spouse; }
        set
        {
            this.spouse = value;
            if (value != null)
            {
                value.spouse = this;
            }
        }
    }
}

The main trouble with this class, seen from AutoFixture's perspective, is the circular reference exposed by the Spouse property. When AutoFixture attempts to create an anonymous instance of Person, it will create anonymous values for all writable properties, and that includes the Spouse property, so it attempts to create a new instance of the Person class and assign values to all public properties, including the Spouse property, etc.

In other words, this line of code throws a StackOverflowException:

var person = fixture.CreateAnonymous<Person>();

If you would still like to have anonymous values assigned to Name and BirthDay, you can use the Without method:

var person = fixture.Build<Person>()
    .Without(p => p.Spouse)
    .CreateAnonymous();

This will give you an anonymous instance of the Person class, but with the Spouse property still with its default value of null.

Several calls to Without can be chained if you want to skip more than one property.



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

Monday, 17 August 2009 19:33:40 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!
Published: Monday, 17 August 2009 19:33:40 UTC