2つの既知の値の間のランダムな整数を出力する、作成したアルゴリズムのJUnitテストを作成する必要があります。
出力値がこれらの2つの整数の間にある(またはない)ことを表明するJUnitテスト(つまり、assertEqualsのようなテスト)が必要です。
つまり、値が5と10の場合、出力は5から10の間のランダムな値になります。テストが正の場合、数値は2つの値の間にあり、そうでない場合はそうではありませんでした。
@Test
public void randomTest(){
int random = randomFunction();
int high = 10;
int low = 5;
assertTrue("Error, random is too high", high >= random);
assertTrue("Error, random is too low", low <= random);
//System.out.println("Test passed: " + random + " is within " + high + " and + low);
}
junit メソッドを使用できますassertThat
(以降JUnit 4.4
)
http://www.vogella.com/tutorials/Hamcrest/article.htmlを参照してください。
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
……
@Test
public void randomTest(){
int random = 8;
int high = 10;
int low = 5;
assertThat(random, allOf(greaterThan(low), lessThan(high)));
}
また、1 つのパラメーターが object で、もう 1 つがプリミティブであるようなケースも発生する可能性がありますが、これも機能せず、プリミティブをオブジェクトに変更するだけですべて設定されます。
例えば:
Request.setSomething(2);// which is integer field
Integer num = Request.getSomething();
//while testing give the object i.e num
assertEquals(Request.getSomething(),num);