3

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);
bkqc
  • 831
  • 6
  • 25

2 Answers2

3

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();
Community
  • 1
  • 1
bkqc
  • 831
  • 6
  • 25
1

You can generate unique integers (lets say days) and then add it to some min date:

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

But I'm not sure that AutoFixture guarantees that all generated values will be unique (see this issue for example)

Alexander
  • 11
  • 3
  • Interesting answer. Not really in the direction I anticipated but it could do it. On the other hand, I'd like to keep the randomness of all dates. If nothing else comes in, I'll give you the credit. As for the uniqueness, you are right as it is mentioned in this post by the author (https://stackoverflow.com/a/35174444/955444) – bkqc Nov 08 '19 at 20:26