如何使用Rest-Assured请求POST API发送令牌和主体值?

时间:2019-04-10 13:29:50

标签: java cucumber rest-assured qa

我正在尝试使用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": ""

}

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

1 个答案:

答案 0 :(得分:2)

您通过POST发送了不正确的正文。

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

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

  

{“客户”:{password =密码,customer = 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);