Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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);
like image 421
bkqc Avatar asked Oct 16 '25 13:10

bkqc


1 Answers

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();
like image 122
bkqc Avatar answered Oct 18 '25 07:10

bkqc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!