如何使用 AutoFixture 获取不同的日期 (yyyy-mm-dd)

How to get distinct dates (yyyy-mm-dd) using AutoFixture

我有一个测试用例,我需要 4 个不同的日期来构建我的对象。 我发现的一切似乎都表明 AutoFixture 总是生成独特的元素,但问题是当它生成日期时,它会考虑到滴答声的所有内容。结果是,当我对结果执行 .ToShortDateString() 时,我可能会得到重复的结果。

我知道我可以循环直到我只得到不同的值,但感觉不对。

目前,我拥有的是:

string[] dates;
do
{
  dates = _fixture.CreateMany<DateTime>(4).Select(d => d.ToShortDateString()).ToArray();
} while (dates.Distinct().Count() != 4);

您可以生成唯一的整数(比方说天),然后将其添加到某个最小日期:

var minDate = _fixture.Create<DateTime>().Date;
var dates = _fixture.CreateMany<int>(4).Select(i => minDate.AddDays(i)).ToArray();

但我不确定 AutoFixture 是否保证所有生成的值都是唯一的(例如参见 [​​=11=])

正如@MarkSeeman 在 中提到的关于数字

Currently, AutoFixture endeavours to create unique numbers, but it doesn't guarantee it. For instance, you can exhaust the range, which is most likely to happen for byte values [...]

If it's important for a test case that numbers are unique, I would recommend making this explicit in the test case itself. You can combine Generator with Distinct for this

所以对于这种特殊情况,我现在使用

string[] dates = new Generator<DateTime>(_fixture)
                     .Select(x => x.ToShortDateString())
                     .Distinct()
                     .Take(4).ToArray();