Rest Assured:Groovy匹配器与JSON float

时间:2017-09-08 13:10:25

标签: java groovy rest-assured

似乎groovy匹配器找不到相等的浮点值。我正在做的是确保在响应正文中有一个具有确切值的地图。

这是代码

Float purchaseAmount = (Float) ((Map) travelSharedData.bookingPackage.get("total")).get("amount");
response.then().body(String.format("response.cashbacks.find() {it.purchaseAmount.amount == %.2f}", purchaseAmount), is(notNullValue()));

JSON

{
    "response": {
        "cashbacks": [
            {
                "date": "09-08-2017T12:56:39.000Z",
                "purchaseAmount": {
                    "amount": 4963.91,
                    "currency": "USD"
                },
                "cashbackAmount": {
                    "amount": 99.28,
                    "currency": "USD"
                },
                "description": "Tulip House Boutique Hotel Bratislava",
                "estimatedAvailable": "10-28-2017T00:00:00.000Z",
                "status": "pending",
                "eventType": "transaction"
            }
]}}

错误

java.lang.AssertionError: 1 expectation failed.
JSON path response.cashbacks.find() {it.purchaseAmount.amount == 4963.91 && it.description == 'Tulip House Boutique Hotel Bratislava'} doesn't match.
Expected: is not null
  Actual: null

当然我可以转换这些值,但我想知道为什么它会失败。

1 个答案:

答案 0 :(得分:0)

正如 @ mike-strobel 所解释的那样,groovy无法找到它,因为浮动本质上是不精确的。

一种解决方法是将等同性比较替换为下一个代码:

Float purchaseAmount = (Float) ((Map) travelSharedData.bookingPackage.get("total")).get("amount");
Float lowerBound = purchaseAmount - 0.01f;
Float upperBound = purchaseAmount + 0.01f;
response.then().body(String.format("response.cashbacks.find() {it.purchaseAmount.amount > %.2f && it.purchaseAmount.amount < %.2f}", lowerBound, upperBound), is(notNullValue()));

这里也是一个很好的解释:What's wrong with using == to compare floats in Java?