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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With