我正在使用localhost测试API,在手动测试中使用Postman进行了很好的操作,如下截图所示: Postman
如屏幕截图所示,必须在请求正文中发送用户名和密码,然后API会在响应标头中返回Authentication密钥,并且Status 200 OK。
但是当我尝试自动化测试以查看是否可以从标头响应中检索密钥时,测试因statusCode 404而失败,我甚至无法查看它是否在标头中获得授权。在自动执行此类请求时,是否存在我遗漏的内容?
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
public class reusableMethods {
public static String getSessionKey() {
RestAssured.baseURI = "http://localhost:3000";
Response res =
given().log().all().
header("Content-Type", "application/json").
body("{\n" +
" \"email\": \"admin@test.com.br\",\n" +
" \"password\": \"passw0rd\"\n" +
"}").
when().
post("/api/cms/v1/auth/login").
then().assertThat().
statusCode(200).
extract().response();
String headerValue = res.header("Authorization");
System.out.println(headerValue);
return headerValue;
}
当我运行测试时,我总是得到相同的错误,如下所示:
Request method: POST
Request URI: http://localhost:3000/api/cms/v1/auth
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body:
{
"email": "admin@test.com.br",
"password": "passw0rd"
}
java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <404>.
答案 0 :(得分:0)
您可以使用auth()方法传递身份验证。 它有多个选项,您需要查看哪一个适合您的身份验证。
如果您使用的是OAuth令牌,那么它就像:
Response res = given()
.auth().oauth2("Your token")
.log().all().
header("Content-Type", "application/json").
body("{\n" + " \"email\": \"admin@test.com.br\",\n" +" \"password\": \"passw0rd\"\n" +"}").
when().
post("/api/cms/v1/auth/login").
then().
assertThat().
statusCode(200).extract().response();