Groovy assert with fails even though I see an item in the list

Groovy assert with contains:

assert testList.contains(4)
   |        |
   |        false
   [1, 2, 6, 3, 4]

I'm out of my mind?

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 delete everything except those contained in (4) and contains (6), it fails for one 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 were greatly appreciated.

+4
source share
1 answer

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]

Thus, 6they 4are instances BigDecimal, not Integerinstances.

So, containsit crashes (since you are looking for Integer(6)notBigDecimal(6)

If you change:

            retList.add(number / i)

in

            retList.add(number.intdiv( i ) )

Then your results will remain intact, and your statements will work :-)

By the way, 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 ]
                              }
                          }
}
+6
source

All Articles