8

0〜10の乱数を返すメソッドがあります。

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

このためのJUnitテストをどのように作成しますか?これまでのところ、呼び出しをループに入れて1000回実行し、次の場合にテストに失敗します-数値が0未満-数値が10を超える

すべての数値が同じではないことをどのようにテストできますか?

ディルバート

4

3 に答える 3

3

ランダム性検定は潜在的に複雑です。たとえば、上記のように、1から10までの数字を確実に取得したいですか?均一な分布などを確保したいですか?ある段階で、私はあなたが信頼したいと思うことを提案し、Math.random()あなたが制限/範囲を台無しにしていないことを単に確認します。それは本質的にあなたがしていることです。

于 2013-02-11T11:12:26.127 に答える
3

My answer was already flawed, I needed to return a number from 0-10 but my original post only returned a range from 0-9! Here is how I found that out...

Loop 100k times and make sure that the range is correct, it should be 0-10 (although I've set 10 as a variable so that the code can be re-used).

Also I store the highest and lowest values that were found during the loop and they should be at the extreme ends of the scale.

If the highest and lowest values are the same then that's an indicator that someone has faked a random number return.

The only problem that I see is that it is possible to have a false negative from this test, but it is unlikely.

@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 + ".");
    }

}
于 2013-02-11T12:28:42.073 に答える
1

Java が提供する Math.random() の品質ではなく、コードをテストする必要があります。Java メソッドが適切であると仮定します。すべてのテストは必要ですが、正確さの十分条件ではありません。したがって、Java が提供するメソッドを使用する際のプログラミング エラーの可能性を明らかにするいくつかのテストを選択してください。

次のことをテストできます: 最終的に、一連の呼び出しの後、関数は必要な範囲外の数値を返すことなく、各数字を少なくとも 1 回返します。

于 2015-12-10T12:21:15.303 に答える