在C#中,隨機數(shù)生成器通常使用System.Random
類
Random
實例,并多次調(diào)用Next()
方法以生成隨機整數(shù)。觀察生成的數(shù)字是否在預期的范圍內(nèi)。[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
實例,并生成隨機數(shù)。觀察不同種子值是否產(chǎn)生不同的隨機數(shù)序列。[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
實例,并生成隨機數(shù)。觀察相同種子值是否產(chǎn)生相同的隨機數(shù)序列。[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()
方法的邊界條件,例如傳入最小值和最大值,或者只傳入一個參數(shù)。確保生成的隨機數(shù)在預期的范圍內(nèi)。[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等),你需要根據(jù)該框架的語法和斷言方法進行相應的調(diào)整。