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

使用Rest Assured创建用户时触发NumberFormatException异常求助

解决Rest Assured创建用户时的NumberFormatException异常

问题根源

你遇到的java.lang.NumberFormatException: For input string: "[null, null, null]",本质是接口返回的不是预期的单个用户JSON对象,而是错误信息数组。当你调用getInt("id")时,Rest Assured尝试把数组字符串转成整数,自然抛出异常。

具体问题点

gorest.co.in的用户创建API对请求体字段有严格的格式要求,你的代码里有3处不符合规范:

  • 字段名大小写错误:API要求用小写键名,你写的Name、Gender、Status应该改为name、gender、status
  • gender字段值格式错误:有效值是female(全小写),不是FeMale

修正后的代码

package Day8;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.json.JSONObject;
import org.testng.annotations.Test;
import com.github.javafaker.Faker;

public class CreateUser { 

    @Test
    void test_CreateUser() {
        Faker fake = new Faker(); 
        JSONObject jsonobj = new JSONObject();
        // 修正字段名为小写,匹配API要求
        jsonobj.put("name", fake.name().fullName());
        // 修正gender值为全小写有效值
        jsonobj.put("gender", "female");
        jsonobj.put("email", fake.internet().emailAddress());
        jsonobj.put("status", "active");
        
        String bearer_Token = "你的有效Bearer Token";
        
        // 先验证响应状态码和结构,再提取id
        int id = given()
            .headers("Authorization","Bearer "+bearer_Token)
            .contentType("application/json")
            .body(jsonobj.toString())
        .when()
            .post("https://gorest.co.in/public/v2/users")
        .then()
            .statusCode(201) // 验证创建成功的状态码
            .body("id", notNullValue()) // 验证id字段存在
            .extract()
            .jsonPath()
            .getInt("id");       
        
        System.out.println("创建的用户ID:" + id);         
    }   
}

额外调试建议

如果后续再遇到类似问题,可以在请求后添加日志打印,直接查看完整响应内容,快速定位问题:

.when()
    .post("https://gorest.co.in/public/v2/users")
.then()
    .log().all() // 打印完整响应
    .statusCode(201)
    ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:52:02