【问题标题】:JUnit assert, value is between two integersJUnit 断言,值在两个整数之间
【发布时间】:2013-01-30 22:10:58
【问题描述】:

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

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

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

【问题讨论】:

  • 你不能想出一个逻辑语句来检查两个数字之间的值吗?
  • mmm...assertTrue 条件为(i >= 5) && (i <= 10)?
  • 或者,您可以为所有不在 5 和 10 之间的值执行 assertNotEquals... :-D
  • 或者,您可以编写自己的匹配器并使用 assertThat

标签: java random junit


【解决方案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);
}

【讨论】:

  • 嘿,我觉得自己像个白痴!我很少使用 JUnit,我只是想不出该怎么做。非常感谢:)
【解决方案2】:

你可以使用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)));
}

【讨论】:

  • 这是一个出色的解决方案,因为它在测试失败时提供比assertTrue 更有用的反馈。
【解决方案3】:

你也可能遇到一个参数是对象另一个是原始的情况,这也不起作用,只需将原始更改为对象就可以了。

例如:

Request.setSomething(2);// which is integer field
Integer num = Request.getSomething();

//while testing give the object i.e num 
assertEquals(Request.getSomething(),num);

【讨论】:

    【解决方案4】:

    您可以使用assertEqualsdouble版本,支持delta参数:

    assertEquals(double expected, double actual, double delta)
    

    例子:

    int random = 8;
    int high = 10;
    int low = 5;
    
    assertEquals((high + low) / 2.0, random, (high - low) / 2.0);
    

    【讨论】:

      猜你喜欢
      • 2010-09-22
      • 2011-03-15
      • 1970-01-01
      • 2022-03-23
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多