使用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
相关产品推荐
相关产品推荐

