JUnit 断言,值介于两个整数之间

2022-09-03 08:45:01

我需要为我编写的算法编写一个JUnit测试,该算法输出两个已知值之间的随机整数。

我需要一个JUnit测试(即像测试一样的assertEquals),它断言输出值在这两个整数之间(或不)。

即,我有值5和10,输出将是5到10之间的随机值。如果测试为正,则该数字介于两个值之间,否则不是。


答案 1
@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);
}

答案 2

您可以使用 junit 方法(因为assertThatJUnit 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)));
}

推荐