使用 AutoFixture 3 生成的整数是否唯一?

Are integer numbers generated with AutoFixture 3 unique?

使用 IFixture.Create<int>() 生成的整数是否唯一?

The Wiki says 数字是随机的,但它也告诉我们这一点

The first numbers are generated within the range of [1, 255], as this is a set of values that are valid for all numeric data types. The smallest numeric data type in .NET is System.Byte, which fits in this range.

When the first 255 integers have been used, numbers are subsequently picked from the range [256, 32767], which corresponds to the remaining positive numbers available for System.Int16.

在 GitHub 有两个相关的事情:

https://github.com/AutoFixture/AutoFixture/issues/2

https://github.com/AutoFixture/AutoFixture/pull/7

那些单元测试呢?

https://github.com/AutoFixture/AutoFixture/blob/master/Src/AutoFixtureUnitTest/GeneratorTest.cs#L33

[Theory, ClassData(typeof(CountTestCases))]
public void StronglyTypedEnumerationYieldsUniqueValues(int count)
{
    // Fixture setup
    var sut = new Generator<T>(new Fixture());
    // Exercise system
    var actual = sut.Take(count);
    // Verify outcome
    Assert.Equal(count, actual.Distinct().Count());
    // Teardown
}

https://github.com/AutoFixture/AutoFixture/blob/master/Src/AutoFixtureUnitTest/GeneratorTest.cs#L57

[Theory, ClassData(typeof(CountTestCases))]
public void WeaklyTypedEnumerationYieldsUniqueValues(int count)
{
    // Fixture setup
    IEnumerable sut = new Generator<T>(new Fixture());
    // Exercise system
    var actual = sut.OfType<T>().Take(count);
    // Verify outcome
    Assert.Equal(count, actual.Distinct().Count());
    // Teardown
}

我没有找到说生成的数字是唯一的声明,只有那些暗示它的信息,但我可能是错的。

在[1, 255]范围内生成第一个数字,共有no duplicates present个。超过该范围,目前可能会重复。

This 问题包含有关如何改进内置算法的有用信息。

目前,AutoFixture 努力创建唯一编号,但它不能保证。例如,您可以用尽范围,这对于 byte 值最有可能发生。例如,如果您请求 300 个 byte 个值,您 得到重复项,因为只有 256 个值可供选择。

一旦初始集用完,AutoFixture 将愉快地重用这些值;另一种方法是抛出异常。

如果数字的唯一性对于测试用例很重要,我建议在测试用例本身中明确。为此,您可以将 Generator<T>Distinct 结合使用:

var uniqueIntegers = new Generator<int>(new Fixture()).Distinct().Take(10);

如果您正在使用 AutoFixture.Xunit2,您可以通过测试方法参数请求 Generator<T>

[Theory, AutoData]
public void MyTest(Generator<int> g, string foo)
{
    var uniqueIntegers = g.Distinct().Take(10);
    // more test code goes here...
}