首页 > 解决方案 > 如何使用 Rest-Assured 请求 POST API 发送令牌和正文值?

问题描述

我正在尝试使用 Rest-Assured 和 Java 为 POST API 创建测试自动化。此 POST API 的主体为 Application/JSON,如下所示:

{
    "customer":{
        "email": "teste@mailinator.com"
    },
    "password":"Teste@12"
}

为了提出这个请求,我使用了以下代码,但它返回状态代码“400”,但我在 Postman 上发送相同的信息,它返回“200”:

@And("envio as informacoes da chamada: (.*), (.*), (.*), (.*) e (.*)")
        public void enviarDados (String srtEmail, String srtSenha, String srtAmbiente, String srtAPI, String srtToken) {
HashMap<String,String> postContent = new HashMap<String,String>();
            postContent.put("email", srtEmail);
            postContent.put("password", srtSenha);
            //System.out.println("{\"customer\":" +postContent+ "}");
            given().contentType(ContentType.JSON).header("Authorization", "Bearer"+srtToken).header("Content-Type", "application/json").
            //with().body(postContent).
            with().body("{\"customer\":" +postContent+ "}").
            when().post(srtAmbiente+srtAPI).
            then().statusCode(200); 
}

“400”响应是:

{
"status": 400,
"message": "Malformed request",
"additional_error": ""

}

结构对吗?您认为缺少什么?谢谢!

标签: javacucumberrest-assuredqa

解决方案


您使用 POST 发送的正文不正确。

//This line will not serialize HashMap to JSON, but call toString()
.body("{\"customer\":" +postContent+ "}")

结果,您的有效负载将如下所示:

{“客户”:{密码=密码,客户=example@example.com}}

这不是有效的 JSON。尝试这个:

Map<String, String> emailContent = new HashMap<>();
emailContent.put("email", "example@example.com");
Map<String, Object> postContent = new HashMap<>();
postContent.put("customer", emailContent);
postContent.put("password", "password");
given().contentType(ContentType.JSON)
    .header("Authorization", "Bearer "+srtToken)
    .with().body(postContent)
    .when().post(srtAmbiente+srtAPI)
    .then().statusCode(200); 

推荐阅读