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

TestNG DataProvider与@Test方法参数不匹配问题排查(Rest Assured)

TestNG DataProvider 参数类型不匹配问题解决

问题原因

从错误日志的参数列表可明确:DataProvider从Excel读取的所有参数均为String类型,但测试方法testGen中定义了int documentNumber、long birthDate、long expirationDate三个非String类型入参。TestNG不会自动完成字符串到数值类型的转换,因此触发MethodMatcherException,提示参数不匹配。

解决方案

在DataProvider读取Excel数据时,对对应列的字符串进行类型转换,转为测试方法所需的int或long类型。

修改后的DataProvider代码

@DataProvider(name = "data_ids")
public Object[][] dataForPost() throws IOException{
    
    int numFiles = search("C:\\Users\\LP\\eclipse-workspace\\RestAssuredAutomation\\Request_Files");
    String names[] = searchnames("C:\\Users\\LP\\eclipse-workspace\\RestAssuredAutomation\\Request_Files");
    String jsons[] = new String[numFiles];
    for (int i=0; i<=numFiles - 1;i++) {
        byte[] b = Files.readAllBytes(Paths.get("Request_Files\\" + names[i]));
        String inputrval = new String(b);
        jsons[i] = inputrval;
    }
    
    String excelPath = "./MyData/IDsData.xlsx";
    String sheetName = "Data";
    ExcelUtils excel = new ExcelUtils(excelPath,sheetName);
    
    int rowCount = ExcelUtils.getRowCount();
    Object data[][] = new Object[rowCount][11];
    
    for(int i=0; i<=rowCount-1;i++) {
        data[i][0] = ExcelUtils.getCellData(i, 0);
        data[i][1] = ExcelUtils.getCellData(i, 1);
        // 转换为int类型
        data[i][2] = Integer.parseInt(ExcelUtils.getCellData(i, 2));
        data[i][3] = ExcelUtils.getCellData(i, 3);
        // 处理科学计数法字符串,转换为long类型
        data[i][4] = (long) Double.parseDouble(ExcelUtils.getCellData(i, 4));
        data[i][5] = ExcelUtils.getCellData(i, 5);
        // 转换为long类型
        data[i][6] = Long.parseLong(ExcelUtils.getCellData(i, 6));
        data[i][7] = ExcelUtils.getCellData(i, 7);
        data[i][8] = ExcelUtils.getCellData(i, 8);
        data[i][9] = ExcelUtils.getCellData(i, 9);
        data[i][10] = ExcelUtils.getCellData(i, 10);
    }
    
    return data;
}

注意事项

  1. 对于Excel中以科学计数法存储的数值(如错误日志中的7.84198E+14),需先用Double.parseDouble解析,再转为long类型,避免直接用Long.parseLong抛出异常。
  2. 如果Excel中存在空值或非数值内容,转换时会抛出NumberFormatException,建议添加异常处理逻辑,或提前校验Excel数据的合法性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:45:31