Can Autofixture.Create<int> return a negative value?
The author of Autofixture discusses this on his blog. This post specifies that the current implementation will always return positive numbers since they are deemed "safer" in general, so I don't think this will change in the near future.
The whole point of AutoFixture is to generate anonymous test data. You are asking for an integer which can be a negative number. To be 100% safe, I wouldn't rely on the implicit assumption that all future implementations only return positive numbers. You can make this more explicit by providing a custom SpecimenBuilder:
fixture.Customizations.Add(new PositiveIntegerBuilder());
More information about custom specimen builders can be found here.
As user prgmtc
points out, one option is through a custom ISpecimenBuilder
.
Another option is to supply a custom range, by using the built-in RandomNumericSequenceGenerator
class, as shown below:
[Fact]
public void FixtureCreatesNegativeNumbers()
{
var fixture = new Fixture();
fixture.Customizations.Add(
new RandomNumericSequenceGenerator(-900, -100));
var i = fixture.Create<int>();
// Prints -> -711
var l = fixture.Create<long>();
// Prints -> 618
var f = fixture.Create<float>();
// Prints -> -78.0
}