首页 > 解决方案 > 导致 assertEquals 的整数上预期/实际值的微小差异失败

问题描述

我正在编写一个自动化测试来确认 sku/cart 值是否正确,例如 SKU * 数量 = 总计。有时(在同一站点的特定区域版本 epsacily 上)测试会失败,因为十进制值的差异很小,例如

(本例中数量为 20,sku 值为 33.92,预期总数为 678.40)

java.lang.AssertionError:预期:678.3999633789062 实际:678.4000244140625

显然,计算在某些时候会进行,但仍然非常接近,也不需要将计算进行到小数点后 2 位以上。

我已经尝试限制在 Assert.assertEquals 计算单价和数量与总数相比之前从元素获取数量和价格值的方法中使用的小数位数无济于事。主要在 'get' 值方法中使用 .NumberFormat

这是黄瓜/小黄瓜步骤的代码

@Then("^the SKU cart Price reflects the unit price times the quantity value$")
    public void theSKUCartPriceReflectsTheUnitPriceTimesTheQuantityValue() {
        itemsInTheBasket_page.waitForCalcResult();
System.out.println(itemsInTheBasket_page.getfirstcartQuantityValue());     System.out.println(itemsInTheBasket_page.getUnitPriceOfFirstItemInCart());
System.out.println(itemsInTheBasket_page.getfirstCartItemPriceValue());
Assert.assertEquals(itemsInTheBasket_page.getfirstcartQuantityValue() * itemsInTheBasket_page.getUnitPriceOfFirstItemInCart(), itemsInTheBasket_page.getfirstCartItemPriceValue(), 0.0);
    }
``


And the code for the for methods used above

 public void waitForCalcResult() {
        Waits.clickable(driver, costCalcResult, 10);
    }


public int getfirstcartQuantityValue() {
        Waits.visible(driver, firstCartItemQuantityField, 5);
        return Integer.parseInt(firstCartItemQuantityField.getAttribute("value"));

    }

public float getUnitPriceOfFirstItemInCart() {
        Waits.visible(driver,firstCartSKUUnitPriceValue, 5);
        String unitValue = firstCartSKUUnitPriceValue.getText();
        unitValue = unitValue.replaceFirst(",", ".");
        unitValue = unitValue.replaceFirst(" ", "");
        unitValue = unitValue.replaceFirst("€", "");
        unitValue = unitValue.replaceAll("[$]", "");
        unitValue = unitValue.replaceAll("£", "");
        return Float.valueOf(unitValue);
    }

 public float getfirstCartItemPriceValue() {
        Waits.visible(driver,firstCartItemPriceValue,5);
        String PriceValue = firstCartItemPriceValue.getText();
        PriceValue = PriceValue.replaceFirst(",", ".");
        PriceValue = PriceValue.replaceFirst(" ", "");
        PriceValue = PriceValue.replaceFirst("€", "");
        PriceValue = PriceValue.replaceAll("[$]", "");
        PriceValue = PriceValue.replaceAll("£", "");
        return Float.valueOf(PriceValue);
    }

标签: java

解决方案


推荐阅读