12

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
Adanay Martín
  • 397
  • 1
  • 3
  • 15

3 Answers3

16

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);
Peter Holmes
  • 622
  • 4
  • 5
  • 1
    I think this does work for negative min and max, as long as min < max. One drawback compared with AutoFixture's usual behavior, however, is that there is no attempt to return distinct values in consecutive calls. – Ralph Gonzalez Nov 10 '20 at 20:29
7

Yes, there is:

// Install-Package AutoFixture.Xunit - or -
// Install-Package AutoFixture.Xunit2

using System;
using System.ComponentModel.DataAnnotations;
using Xunit;

[Theory, AutoData]
public void ActualIsInTestRange([Range(99, 111)]int actual)
{
    Assert.InRange(actual, 99, 111);
}
Nikos Baxevanis
  • 10,868
  • 2
  • 46
  • 80
  • 3
    I don't get the answer. If my understanding is right, the question asks for a way to create a value in a specified range. But the answer is about checking that a value is in a specifier range ... – Psddp Jul 30 '18 at 21:00
  • The check is there for you to see what's going on, that the `actual` value was indeed generated in the specified range. – Nikos Baxevanis Aug 01 '18 at 04:06
  • 10
    This does not answer the question. Instead it shows how to do it using a different library. – Antoine Aubry Sep 21 '18 at 11:39
  • As an alternative, you may use the built-in `Generator` and LINQ, as I've answered [here](https://stackoverflow.com/a/32782299/467754). – Nikos Baxevanis Sep 22 '18 at 07:36
-1

You can use extension method like this:


public static int CreateNumebrFromRange(this IFixture fixture,int min, int max)
{
   var radom = new Random();
   return radom.Next(min, max);
}
MKasprzyk
  • 503
  • 5
  • 17
  • This is not an appropriate use of an extension method. The method signature indicates that it extends `IFixture`, but the method isn't actually doing anything with that type at all, i.e. it's not really extending that type. You could just as well have a static helper class that does the same. See @peterholmes' answer for an appropriate extension method implementation. – Moss Jul 31 '23 at 23:36