3

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?

Nathan A
  • 11,059
  • 4
  • 47
  • 63
  • Internally AutoFixture use Guid as a value for generating random string. I will just do this line of code `return _createString ? "test" : Guid.Empty.ToString();` – CodeNotFound Nov 09 '15 at 22:54
  • @CodeNotFound `String` was just an example, and I want a null string, not an empty string, or an empty guid. I want to return null for several types of objects, as it's a very valid test case in many test scenarios. – Nathan A Nov 10 '15 at 01:58
  • AutoFixture is an opinionated library, and one of the opinions it holds is that [nulls are invalid return values](http://stackoverflow.com/a/18170070/467754). – Nikos Baxevanis Nov 10 '15 at 06:15
  • This looks like a bug. Will investigate further... – Mark Seemann Nov 10 '15 at 07:29

1 Answers1

5

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

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736