Reputation: 428
Groovy assert with contains:
assert testList.contains(4)
| |
| false
[1, 2, 6, 3, 4]
Am I going crazy?
This is the test code:
List testList = tester.getFactors(12)
assert testList.size() == 5
assert testList.contains(1)
assert testList.contains(2)
assert testList.contains(3)
assert testList.contains(4)
assert testList.contains(6)
If I remove everything except the contains(4) and contains(6) it fails for either or both of them.
This is the getFactors method:
List getFactors(int number)
{
def retList = new ArrayList();
(1..Math.sqrt(number)).each() { i ->
if(number % i == 0)
{
//add both the number and the division result
retList.add(i)
if(i>1)
retList.add(number / i)
}
}
retList;
}
Any thoughts greatly appreciated.
Upvotes: 4
Views: 1284
Reputation: 171114
If you do:
println getFactors( 12 )*.class.name
You can see:
[java.lang.Integer, java.lang.Integer, java.math.BigDecimal, java.lang.Integer, java.math.BigDecimal]
So the 6
and the 4
are BigDecimal
instances, not Integer
instances
So the contains
fails (as you are looking for Integer(6)
not BigDecimal(6)
If you change:
retList.add(number / i)
to:
retList.add(number.intdiv( i ) )
Then your results will stay as Integers, and your asserts should work :-)
BTW, just for fun, your function can be rewritten as:
List getFactors( int number ) {
(1..Math.sqrt(number)).findAll { i -> number % i == 0 }
.collectMany { i ->
if( i > 1 ) {
[ i, number.intdiv( i ) ]
}
else {
[ i ]
}
}
}
Upvotes: 6