Randomizer
Randomizer returns a set of random _values in a repeatable
way, to allow re-running of tests if necessary.
This class is an internal framework class used for setting up tests.
It is used to generate random test parameters, at the time of loading
the tests. It also generates seeds for use at execution time, when
creating a RandomGenerator for use by the test.
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NUnit.Framework.Internal
{
public class Randomizer : Random
{
private static Random seedGenerator;
private static Dictionary<MemberInfo, Randomizer> randomizers = new Dictionary<MemberInfo, Randomizer>();
public static int InitialSeed { get; set; }
public static Randomizer GetRandomizer(MemberInfo member)
{
if (randomizers.ContainsKey(member))
return randomizers[member];
Randomizer randomizer = CreateRandomizer();
randomizers[member] = randomizer;
return randomizer;
}
public static Randomizer GetRandomizer(ParameterInfo parameter)
{
return GetRandomizer(parameter.Member);
}
public static Randomizer CreateRandomizer()
{
if (seedGenerator == null)
seedGenerator = new Random(InitialSeed);
return new Randomizer(seedGenerator.Next());
}
public Randomizer()
: base(InitialSeed)
{
}
public Randomizer(int seed)
: base(seed)
{
}
public double[] GetDoubles(int count)
{
double[] array = new double[count];
for (int i = 0; i < count; i++) {
array[i] = NextDouble();
}
return array;
}
public object[] GetEnums(int count, Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException($"""{enumType}""");
Array values = Enum.GetValues(enumType);
object[] array = new Enum[count];
for (int i = 0; i < count; i++) {
array[i] = values.GetValue(Next(values.Length));
}
return array;
}
public double[] GetDoubles(double min, double max, int count)
{
double num = max - min;
double[] array = new double[count];
for (int i = 0; i < count; i++) {
array[i] = NextDouble() * num + min;
}
return array;
}
public int[] GetInts(int min, int max, int count)
{
int[] array = new int[count];
for (int i = 0; i < count; i++) {
array[i] = Next(min, max);
}
return array;
}
}
}