Nathan A
Nathan A

Reputation: 11319

How to Customize AutoFixture to Return Null Sometimes

In this sample code, I want to configure a Fixture object to return null for strings half of the time.

void Test()
{
    var fixture = new Fixture();

    fixture.Customize<string>(x => x.FromFactory(CreateString));

    var str1 = fixture.Create<string>();

    //error occurs here when string should come back null
    var str2 = fixture.Create<string>(); 
}

bool _createString = false;

string CreateString()
{
    _createString = !_createString;

    return _createString ? "test" : null;
}

The problem is, whenever my factory returns null, I get an InvalidOperationException:

The specimen returned by the decorated ISpecimenBuilder is not compatible with System.String.

This happens for any type where I return null inside a factory. Is there any way to configure AutoFixture to return null for a requested object?

Upvotes: 3

Views: 5803

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233125

This was a defect. It ought to be addressed in AutoFixture 3.36.11.

Upvotes: 5

Related Questions