I have an existing class that extends a Number & implements Comparable, and I have been using this class extensively - including in my test classes (Junit & Spock). I have also been comparing instances of this class using == operator in the test classes.
As I understand it, Groovy will not use .equals() for comparison of classes which implements Comparable. Furthermore, after trawling Groovy code, I also found out that my class will be compared using Integer (hence losing decimal points, etc) - as it is not Floating point, BigDecimal, BigInteger, Long. i.e. Integer is the fallback.
To overcome this problem, I tried to do metaclass programming on Groovy's NumberMath class.
class Test2 {
@Test
void blah(){
NumberMath.metaClass.static.compareTo = { Number left, Number right ->
println "982374"
return 123
}
def num1 = new Decimal("9.01")
def num2 = new Decimal("9.02")
// this prints 982374
println NumberMath.compareTo(num1, num2)
// this doesnt print 982374
num1 == num2
}
}
But this doesnt seem to work (as shown in the snippet above). The == operator doesnt call the compareTo method which I have provided in the test. Have I missed something here?
Thanks in advance!
Regards,
Alex