在C#中,随机数生成器通常使用System.Random
类
Random
实例,并多次调用Next()
方法以生成随机整数。观察生成的数字是否在预期的范围内。[Test]
public void GenerateRandomIntegers()
{
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int randomNumber = random.Next(1, 100);
Assert.IsTrue(randomNumber >= 1 && randomNumber <= 100);
}
}
Random
实例,并生成随机数。观察不同种子值是否产生不同的随机数序列。[Test]
public void DifferentSeedsProduceDifferentSequences()
{
Random random1 = new Random(123);
Random random2 = new Random(456);
for (int i = 0; i < 10; i++)
{
int randomNumber1 = random1.Next();
int randomNumber2 = random2.Next();
Assert.AreNotEqual(randomNumber1, randomNumber2);
}
}
Random
实例,并生成随机数。观察相同种子值是否产生相同的随机数序列。[Test]
public void SameSeedProducesSameSequence()
{
Random random1 = new Random(123);
Random random2 = new Random(123);
for (int i = 0; i < 10; i++)
{
int randomNumber1 = random1.Next();
int randomNumber2 = random2.Next();
Assert.AreEqual(randomNumber1, randomNumber2);
}
}
Next()
方法的边界条件,例如传入最小值和最大值,或者只传入一个参数。确保生成的随机数在预期的范围内。[Test]
public void TestBoundaryConditions()
{
Random random = new Random();
int randomNumber1 = random.Next(0); // No upper bound specified
Assert.IsTrue(randomNumber1 >= 0);
int randomNumber2 = random.Next(10, 100); // Specify both lower and upper bounds
Assert.IsTrue(randomNumber2 >= 10 && randomNumber2 < 100);
}
[Test]
public void TestDistributionUniformity()
{
const int numGroups = 10;
const int numIterations = 10000;
int[] groups = new int[numGroups];
Random random = new Random();
for (int i = 0; i < numIterations; i++)
{
int randomNumber = random.Next(numGroups);
groups[randomNumber]++;
}
double expectedCount = numIterations / (double)numGroups;
double tolerance = expectedCount * 0.1; // Allow 10% tolerance
for (int i = 0; i < numGroups; i++)
{
Assert.IsTrue(Math.Abs(groups[i] - expectedCount)< tolerance, $"Group {i} has an unexpected count: {groups[i]}");
}
}
请注意,这些测试方法使用了NUnit测试框架。如果你使用其他测试框架(如MSTest、xUnit等),你需要根据该框架的语法和断言方法进行相应的调整。