Create anonymous enum value from a subset of all values
Asked Answered
M

1

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, ...

Mccarty answered 6/1, 2014 at 18:46 Comment(4)
Here is one way to do it.Hosanna
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.Mccarty
Which version of AutoFixture are you using? With AutoFixture 3, if you do fixture.Create<Statuses>() (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 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...Hosanna
Unfortunately I have to stick with 2.15.2.0... Once I get home I'll check with the latest one. Thanks!Mccarty
B
35

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.

Brigadier answered 7/1, 2014 at 15:9 Comment(4)
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?Reactive
@Schneider Complicated. New question, please.Brigadier
Thanks Mark. Here is the qn #41629019Reactive
You can even do fixture.Create<Generator<Statuses>>().First(s => s != Statuses.Pending)Evolute

© 2022 - 2024 — McMap. All rights reserved.