繁体   English   中英

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

[英]Writing a JUnit test for a random number generator

我有返回0和10之间的随机数的方法。

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

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

我如何测试所有数字不仅仅是相同的,即

迪尔伯特

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

我的答案已经存在缺陷,我需要从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 + ".");
    }

}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM