JUnit断言,值在两个整数之间

Dan*_*nMc 14 java random junit

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

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

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

Sim*_*ant 26

@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);
}
Run Code Online (Sandbox Code Playgroud)

  • 嘿,我觉得自己像个白痴!我很少使用JUnit,我只是想不起怎么做.非常感谢 :) (3认同)

fei*_*ong 18

你可以使用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;
Run Code Online (Sandbox Code Playgroud)

......

@Test
public void randomTest(){
    int random = 8;
    int high = 10;
    int low = 5;
    assertThat(random, allOf(greaterThan(low), lessThan(high)));
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个优秀的解决方案,因为它在测试失败时提供比`assertTrue`更有用的反馈. (2认同)