Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
Robba Avatar asked Jul 25 '16 10:07

Robba


2 Answers

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...
}
like image 125
Mark Seemann Avatar answered Nov 10 '22 19:11

Mark Seemann


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

like image 2
Serhii Shushliapin Avatar answered Nov 10 '22 19:11

Serhii Shushliapin