Robba
Robba

Reputation: 8324

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

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.

Upvotes: 7

Views: 5549

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233125

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...
}

Upvotes: 17

Serhii Shushliapin
Serhii Shushliapin

Reputation: 2708

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

Upvotes: 2

Related Questions