Search code examples
c#autofixture

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


I have a test case where I need 4 distinct dates to build my objects. Everything I found seem to tell that AutoFixture always generate unique elements but the thing is when it generates dates, it does so considering everything down to ticks. The result is that when I do .ToShortDateString() on the result, I may end up with duplicated results.

I know I could loop until I get only distinct values but it doesn't feel right.

For now, what I have is:

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

Solution

  • As mentioned by @MarkSeeman in this post about numbers

    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

    So for this specific situation, I now use

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