19

Let's say we have an enum type defined as:

enum Statuses
{
    Completed,
    Pending,
    NotStarted,
    Started
}

I'd like to make Autofixture create a value for me other than e.g. Pending.

So (assuming round-robin generation) I'd like to obtain:

Completed, NotStarted, Started, Completed, NotStarted, ...

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
dzendras
  • 4,721
  • 1
  • 25
  • 20
  • Here is [one way to do it](http://stackoverflow.com/a/17117080/467754). – Nikos Baxevanis Jan 06 '14 at 21:03
  • Unfortunately does not work: AutoFixture was unable to create an instance from Ploeh.AutoFixture.Kernel.ISpecimenBuilderComposer, most likely because it has no public constructor, is an abstract or non-public type. – dzendras Jan 07 '14 at 09:58
  • Which version of AutoFixture are you using? With AutoFixture 3, if you do `fixture.Create()` (where `fixture` is a `new Fixture()` instance) you will get each `Statuses` enum value in a round-robin fashion. You won't even need the [link](http://stackoverflow.com/a/17117080/467754) I previously mentioned. If that doesn't work then it would be great if you can update the question with some code that reproduces what you describe... – Nikos Baxevanis Jan 07 '14 at 12:32
  • Unfortunately I have to stick with 2.15.2.0... Once I get home I'll check with the latest one. Thanks! – dzendras Jan 07 '14 at 12:35

1 Answers1

33

The easiest way to do that is with AutoFixture's Generator<T>:

var statuses = fixture
    .Create<Generator<Statuses>>()
    .Where(s => Statuses.Pending != s)
    .Take(10);

If you only need a single value, but want to be sure that it's not Statuses.Pending, you can do this:

var status = fixture
    .Create<Generator<Statuses>>()
    .Where(s => Statuses.Pending != s)
    .First();

There are other ways, too, but this is the easiest for an ad-hoc query.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • I am interested in doing something similar but totally generically for any Enum type. I want to ignore any values based on string matches e.g. Unknown or Uninitialised. Is there a way to intercept the values returned by EnumGenerator? – Jack Ukleja Jan 13 '17 at 06:01
  • 1
    @Schneider Complicated. New question, please. – Mark Seemann Jan 13 '17 at 06:05
  • Thanks Mark. Here is the qn http://stackoverflow.com/questions/41628519/how-to-exclude-certain-enumerations-from-all-enumeration-types – Jack Ukleja Jan 13 '17 at 06:21
  • 1
    You can even do `fixture.Create>().First(s => s != Statuses.Pending)` – Jim Aho Feb 05 '19 at 20:06