我正在尝试使用Rest-Assured和Java为POST API创建测试自动化。此POST API的主体为Application / JSON,如下所示:
{
"customer":{
"email": "[email protected]"
},
"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": ""
}
结构对吗?有什么你认为缺少的东西?谢谢!
您使用POST发送了错误的正文。
//This line will not serialize HashMap to JSON, but call toString()
.body("{\"customer\":" +postContent+ "}")
因此,您的有效负载将以这种方式显示:
{“customer”:{password = password,customer = [email protected]}}
这不是有效的JSON。试试这个:
Map<String, String> emailContent = new HashMap<>();
emailContent.put("email", "[email protected]");
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);