Groovy断言包含失败,即使我可以看到列表中的项目
发布时间:2020-12-14 16:24:01 所属栏目:大数据 来源:网络整理
导读:Groovy断言包含: assert testList.contains(4) | | | false [1,2,6,3,4] 我疯了吗? 这是测试代码: List testList = tester.getFactors(12) assert testList.size() == 5 assert testList.contains(1) assert testList.contains(2) assert testList.contai
Groovy断言包含:
assert testList.contains(4) | | | false [1,2,6,3,4] 我疯了吗? 这是测试代码: 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) 如果我删除除contains(4)和contains(6)之外的所有内容,则它们中的任何一个或两个都会失败. 这是getFactors方法: 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; } 任何想法都非常感激. 解决方法
如果你这样做:
println getFactors( 12 )*.class.name 你可以看到: [java.lang.Integer,java.lang.Integer,java.math.BigDecimal,java.math.BigDecimal] 所以6和4是BigDecimal实例,而不是Integer实例 所以包含失败(因为你正在寻找整数(6)而不是BigDecimal(6) 如果你改变: retList.add(number / i) 至: retList.add(number.intdiv( i ) ) 然后你的结果将保持为整数,你的断言应该工作:-) 顺便说一句,只是为了好玩,你的功能可以改写为: List getFactors( int number ) { (1..Math.sqrt(number)).findAll { i -> number % i == 0 } .collectMany { i -> if( i > 1 ) { [ i,number.intdiv( i ) ] } else { [ i ] } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |