Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock - approximate comparisions

I’ve been looking for the Spock equivalent of the following convenience method in JUnit whereby you can do “approximate” comparisons. Does anyone know if such a thing exists?

/**
 * Asserts that two doubles or floats are equal to within a positive delta.
 */
assertEquals(double expected, double actual, double delta) 
like image 436
dre Avatar asked Sep 08 '25 03:09

dre


2 Answers

There is build in function for that, described in official docs:

when:
def x = computeValue()

then:
expect x, closeTo(42, 0.01)

Check the specs.

like image 179
Michal_Szulc Avatar answered Sep 10 '25 20:09

Michal_Szulc


I don't know if there's a Spock equivalent but it's easy to write your own

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)
  }
}

In practice, you'd probably want to make compareApproximately reusable across specs by defining it in a trait, subclass of Specification, or a static method in a utility class.

like image 35
Dónal Avatar answered Sep 10 '25 18:09

Dónal