How can I use AutoFixture to create an object but not fill out any properties
Asked Answered
B

2

7

Using AutoFixture I can easily create an instance of a data object using the Create method like so:

_fixture.Create<FilterItems>()

Using this technique I am protected for any changes in the constructor that may come in the future, but it also fills out all properties which in this case (because it's a collection of filters) is not desired.

Is there any way to just tell AutoFixture to create the object, but not fill out any properties?

I know there's a Without method to skip a field, but using that means I have to keep adding to it whereas I'd rather just start with an empty object and add to it if a test needs it.

Bimbo answered 25/7, 2016 at 10:34 Comment(0)
K
17

There are plenty of ways to do that.

You can do it as a one-off operation:

var fi = fixture.Build<FilterItems>().OmitAutoProperties().Create();

You can also customize the fixture instance to always omit auto-properties for a particular type:

fixture.Customize<FilterItems>(c => c.OmitAutoProperties());

Or you can completely turn off auto-properties:

fixture.OmitAutoProperties = true;

If you're using one of the unit testing Glue Libraries like AutoFixture.Xunit2, you can also do it declaratively:

[AutoData]
public void MyTest([NoAutoProperties]FilterItems fi)
{
    // Use fi here...
}
Kokaras answered 25/7, 2016 at 11:13 Comment(1)
Wow, I was just watching your advanced course on Pluralsight. Amazing to get an answer from the author himself in 4 mins no less! Thanks for the answer, I totally misunderstood the AutoProperties documentation which seems to imply (to me) that this feature will skip properties that have a default value and thus not skip values that would otherwise result in a value of default(<type>).Bimbo
T
2

You should call _fixture.OmitAutoProperties = true; before creating a specimen.

Trochelminth answered 25/7, 2016 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.