【问题标题】:Spock - approximate comparisionsSpock - 近似比较
【发布时间】:2018-11-22 14:19:09
【问题描述】:

我一直在寻找与 JUnit 中以下便捷方法等效的 Spock,您可以通过它进行“近似”比较。有谁知道这样的事情是否存在?

/**
 * Asserts that two doubles or floats are equal to within a positive delta.
 */
assertEquals(double expected, double actual, double delta) 

【问题讨论】:

  • 您可能想要使用 Hamcrest 匹配器。

标签: grails junit spock


【解决方案1】:

有一个内置函数,在official docs 中描述:

when:
def x = computeValue()

then:
expect x, closeTo(42, 0.01)

检查specs

【讨论】:

  • 这更具体地回答了这个问题。谢谢@Michal_Szulc
  • 另请参阅 Spock 发布说明,其中提到了 Hamcrest 支持 herethere
【解决方案2】:

我不知道是否有 Spock 等价物,但很容易自己编写

class Foo extends Specification {

  private boolean compareApproximately(Number expected, Number actual, Number delta) {
    Math.abs(expected - actual) <= delta
  }

  def "approximate test"() {
    expect:
    compareApproximately(4, 4.5, 1)
    !compareApproximately(4, 4.5, 0.1)
  }
}

在实践中,您可能希望通过将 compareApproximately 定义在 trait、Specification 的子类或实用程序类中的静态方法中来使 compareApproximately 可跨规范重复使用。

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多