为随机数生成器编写JUnit测试

时间:2013-02-11 11:08:13

标签: java random junit

我有一个方法,它返回0到10之间的随机数。

public int roll(){
    int pinsKnockedDown = (int) (Math.random() * 10);
    return pinsKnockedDown;
}

我如何为此编写JUnit测试?到目前为止,我已将调用置于循环中,因此它运行1000次并且如果失败则进行测试 - 数字小于0 - 数量超过10

我如何测试所有数字都不一样,即

Dilbert

3 个答案:

答案 0 :(得分:2)

Randomness tests可能很复杂。例如在上面你只是想确保你得到1到10之间的数字?您想确保均匀分布等吗?在某个阶段,我建议您要信任Math.random(),并确保您没有搞砸限制/范围,这实际上就是您正在做的事情。

答案 1 :(得分:2)

我的答案已经存在缺陷,我需要从0-10返回一个数字,但我原来的帖子只返回0-9的范围!以下是我发现的结果...

循环100k次并确保范围正确,它应该是0-10(尽管我将10设置为变量以便可以重复使用代码)。

此外,我还存储了循环期间找到的最高和最低值,并且位于刻度的最末端。

如果最高值和最低值相同,则表明有人伪造了随机数字返回。

我看到的唯一问题是可能从此测试中得到假阴性,但不太可能。

@Test
public void checkPinsKnockedDownIsWithinRange() {
    int pins;
    int lowestPin = 10000;
    int highestPin = -10000;

    for (int i = 0; i < 100000; i++) {
        pins = tester.roll();
        if (pins > tester.NUMBER_OF_PINS) {
            fail("More than 10 pins were knocked down");
        }
        if (pins < 0) {
            fail("Incorrect value of pins");
        }

        if (highestPin < pins) {
            highestPin = pins;
        }

        if (lowestPin > pins) {
            lowestPin = pins;
        }
    }

    if (lowestPin == highestPin) {
        fail("The highest pin count is the same as the lowest pin count. Check the method is returning a random number, and re-run the test.");
    }

    if (lowestPin != 0) {
        fail("The lowest pin is " + lowestPin + " and it should be zero.");
    }

    if (highestPin != tester.NUMBER_OF_PINS) {
        fail("The highest pin is " + highestPin + " and it should be " + tester.NUMBER_OF_PINS + ".");
    }

}

答案 2 :(得分:1)

您希望测试您的代码,而不是Java提供的Math.random()的质量。假设Java方法很好。所有测试都是必要的,但不是正确性的充分条件。因此,选择一些测试可以发现使用Java提供的方法时可能出现的编程错误。

您可以测试以下内容:最后,在一系列调用之后,该函数至少返回一次数字,而不返回任何超出所需范围的数字。

相关问题