Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a specimen builder to generate enum values from a subset #1219

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

notnotchris
Copy link

@notnotchris notnotchris commented Dec 28, 2020

I'm working on a code base at the moment where it would be useful to be able to restrict the values that are generated for a particular type of enum to a subset of the available values. If I use the TriState enumeration as an example, I might want to exclude the value TriState.First, or alternatively to include only the values TriState.Second and TriState.Third.

Although it is already possible to create a customization with functionality similar to that implemented here I don't think it is particularly obvious how to do so. This would make it relatively easy to create a customization that restricts enum values to a subset, as follows.

internal sealed class ExampleEnumCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customize<TriState>(
            _ => new RestrictedEnumGenerator<TriState>(RestrictedEnum.ExcludeValues(TriState.First)));
    }
}

Admittedly, having to do this may be indicative of a code smell in certain circumstances but I still think it could be useful – particularly for those of use that have to work on existing/legacy code bases from time to time, where the abuse of enums can be quite common. Perhaps it may also be useful to exclude the zero value from an enum, which is often the equivalent of None and may not be expected to occur except in certain conditions.

I'll be using this code, or some variation of it, elsewhere so it won't go to waste if rejected but I thought it might be worth seeing if you think it's worth including in AutoFixture. I didn't think it was worth opening an issue for this so please accept my apologies if I should have done so. I'd be most grateful for your thoughts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant