Groovy 和 Spock : toDouble vs toFloat

标签 groovy spock

我有这个代码:

static def parseString(String inputRow, Particle particle) {
        def map = inputRow.split()
        particle.mass = map[0].toDouble()
        particle.x = map[1].toDouble()
        particle.y = map[2].toDouble()
}

这个测试代码:

static final inputRow = "1 -5.2 3.8"
def particle1 = new Particle()

def "string should be parsed into particles"() {
    when:
    RepulsionForce.parseString(inputRow, particle1);

    then:
    particle1.mass == 1
    particle1.x == -5.2
    particle1.y == 3.8
}

上述测试按原样通过; 但是,当我将 parseString 代码更改为以下代码时:

static def parseString(String inputRow, Particle particle) {
        def map = inputRow.split()
        particle.mass = map[0].toFloat()
        particle.x = map[1].toFloat()
        particle.y = map[2].toFloat()
}

相同的测试因以下错误而失败:

Condition not satisfied:

particle1.x == -5.2
|         | |
|         | false
|         -5.2
Particle@a548695

最佳答案

默认情况下,Groovy 中的 -5.2 是 BigDecimal,因此您将 Bi​​gDecimal 与 Float 对象进行比较。这些通过:

def a = -5.2
def b = "-5.2".toFloat()
assert a != b
assert a.getClass() == BigDecimal
assert b.getClass() == Float
assert a.toFloat() == b

Groovy 接受 BigDecimal 和 Double 之间的比较:

def g = -5.2
def h = "-5.2".toDouble()
assert g == h
assert g.getClass() == BigDecimal
assert h.getClass() == Double

如果您需要进行一些需要精度的计算,您可能最好使用 BigDecimal,因为它们保留它(尽管会降低性能)

def c = -5.2
def d = "-5.2".toBigDecimal()
assert c == d
assert c.getClass() == BigDecimal
assert d.getClass() == BigDecimal

否则,根据 @Tim 的评论,使用 -5.2f,因此针对 Float 对象进行比较:

def e = -5.2f
def f = "-5.2".toFloat()
assert e == f
assert e.getClass() == Float
assert f.getClass() == Float

关于Groovy 和 Spock : toDouble vs toFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962842/

相关文章:

unit-testing - 使用指定的超时验证 Spock 模拟

matlab - 用于在 JVM 上进行富有表现力的、功能丰富的数值计算的工具

testing - 是否可以将 easyb 的 Groovy 与简单的英语场景定义分开?

sql - JSON Grail Groovy 更新 SQL

groovy - JMockit MockUp 在 Spock 测试之间持续存在

unit-testing - 使用 Spock 和 Grails 在全局 stub 类中注入(inject) stub 协作者

java - Grails应用程序无法运行,但未收到任何错误

java - 如何在应用程序中正确运行自定义 Groovy 脚本?

grails - getAll() 在单元测试中不起作用

unit-testing - 使用 Controller 的 Grails Spock 单元测试断言 View