Skip to content

Instantly share code, notes, and snippets.

@Powerz
Created January 31, 2023 20:47
Show Gist options
  • Save Powerz/44e6b544460736cdd761c6dcf8828ef4 to your computer and use it in GitHub Desktop.
Save Powerz/44e6b544460736cdd761c6dcf8828ef4 to your computer and use it in GitHub Desktop.
Random enum generator for AutoFixture.
using AutoFixture.Kernel;
/// <summary>
/// AutoFixture random generator for enums
/// </summary>
public class RandomEnumGenerator : ISpecimenBuilder
{
private static readonly Random _randomizer = Random.Shared;
public object Create(object request, ISpecimenContext context)
{
var type = request as Type;
if (type?.IsEnum != true)
{
return new NoSpecimen();
}
var values = Enum.GetValues(type);
var index = _randomizer.Next(values.Length);
return values.GetValue(index)!;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment