Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture for number ranges

Tags:

c#

autofixture

Is there an easy way to do this with AutoFixture?

var myInt = fixture.Create<int>(min, max);

I would like to know whether or not this is possible with AutoFixture or if I have to instantiate a random object and do the work myself.

In case this is not possible, is there a good reason for not having this feature that I am missing here?

like image 873
Adanay Martín Avatar asked Nov 25 '16 19:11

Adanay Martín


1 Answers

As a one-off you could just do:

var value = fixture.Create<int>() % (max - min + 1) + min;

As a more re-usable approach, you could write an extension method as follows:

public static class FixtureExtensions
{
    public static int CreateInt(this IFixture fixture, int min, int max)
    {
        return fixture.Create<int>() % (max - min + 1) + min;
    }
}

Which can then be used as follows:

var value = fixture.CreateInt(min, max);
like image 167
Peter Holmes Avatar answered Nov 07 '22 04:11

Peter Holmes