You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自动化测试中解析金额文本触发NumberFormatException异常的修复求助

问题修复方案

你遇到的NumberFormatException是因为直接用Integer.parseInt()解析包含小数、空格和货币符号的字符串导致的,同时后续的断言逻辑也存在格式不匹配的问题,以下是具体修复步骤和代码:

错误原因拆解

  • 输入字符串"488.15 EUR"包含非数字字符(空格、"EUR"),且是小数类型,Integer.parseInt()只能解析纯整数字符串,无法处理这些情况。
  • 最终断言时,直接将整数结果和原带格式的字符串比较,类型和格式完全不匹配。

修复方案

步骤1:提取纯数值部分

先用正则表达式过滤掉字符串中的非数字和小数点内容,保留可解析的数值部分:

String rawText = Suma.getText();
// 去掉所有非数字和小数点的字符
String numericStr = rawText.replaceAll("[^\\d.]", ""); // 结果为"488.15"

步骤2:选择合适的数值类型解析

因为原数值是小数,不能用Integer,推荐用BigDecimal(避免浮点精度丢失)或Double:

方式一:用BigDecimal(推荐)

import java.math.BigDecimal;

BigDecimal originalValue = new BigDecimal(numericStr);
BigDecimal resultValue = originalValue.subtract(new BigDecimal("2")); // 488.15 - 2 = 486.15

方式二:用Double

double originalValue = Double.parseDouble(numericStr);
double resultValue = originalValue - 2;

步骤3:转换回原格式并断言

将运算后的数值转回带" EUR"的格式,再和页面更新后的元素文本比较(注意:不要和原文本比较,要验证更新后的内容):

// 用BigDecimal时的格式化
import java.text.DecimalFormat;

DecimalFormat currencyFormat = new DecimalFormat("#.00 EUR");
String expectedText = currencyFormat.format(resultValue);

// 重新获取元素文本(确保是更新后的内容),然后断言
Assert.assertTrue(Suma.getText().equals(expectedText));

如果你确实需要取整数部分减2(即488-2=486)

如果你的预期是只对整数部分做减法,可先提取整数部分再运算:

String rawText = Suma.getText();
String numericStr = rawText.replaceAll("[^\\d.]", "");
// 提取整数部分
int integerPart = (int) Double.parseDouble(numericStr); // 结果为488
int result = integerPart - 2; // 486

// 格式化回对应格式(根据页面显示选择是整数还是带小数)
String expectedText = String.format("%d EUR", result);
Assert.assertTrue(Suma.getText().equals(expectedText));

完整示例代码(BigDecimal版本)

import java.math.BigDecimal;
import java.text.DecimalFormat;

// 1. 获取原始文本并清理
String rawText = Suma.getText();
String numericStr = rawText.replaceAll("[^\\d.]", "");

// 2. 解析并运算
BigDecimal originalValue = new BigDecimal(numericStr);
BigDecimal resultValue = originalValue.subtract(new BigDecimal("2"));

// 3. 格式化并断言
DecimalFormat currencyFormat = new DecimalFormat("#.00 EUR");
String expectedText = currencyFormat.format(resultValue);
Assert.assertTrue(Suma.getText().equals(expectedText));

内容的提问来源于stack exchange,提问作者Catea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:17:35