[英]POST request fails (rest-assured test) Expected response body to be verified as JSON, HTML or XML but no content-type was defined in the response.?
[英]java REST Assured response body with Content-Type: text/html with injected html tags
假設有人開發了以 json 格式返回數據的 rest api,但他沒有將響應Content-Type
設置為application/json
而是text/html
。
現在我已經用 REST Assured 編寫了測試:
given()
.param("username", username)
.param("password", password)
.when()
.get("/authenticate")
.then()
.statusCode(200)
.body("user.id" , hasItem(20));
但它不起作用。 我注銷了響應正文,這就是我得到的:
<html>
<body>{"key":"752E7A74E8F3999BE9EFE3EA0E0DF320","user":{"id":20,"firstName":"K1","lastName":"K1","role":"ROLE_CUSTOMER","phoneNumber":"888888888"},"expirationDate":"2016-08-10T13:52:50+02:00"}</body>
</html>
和錯誤:
FAILED: test_login_as_valid_customer("888888888", "3432")
java.lang.AssertionError: 1 expectation failed.
JSON path key doesn't match.
Expected: 20
Actual:
在 body 標簽之間有我預期的 json 但是 html 標簽來自哪里? 當我在 Postman 或 Paw 或什至在 Web 瀏覽器中測試 api 方法時,我看不到它們的響應(因為它是帶有 url 參數的簡單 GET)。
我懷疑我收到錯誤“JSON 路徑鍵不匹配”。 因為那些標簽。
從最初的問題過去了 3 年,我遇到了同樣的問題,這就是我所得到的。
將響應體包裝成 html 標簽是io.restassured.internal.support.Prettifier
類的工作。 您可以通過以下方式禁用它。
RestAssured.requestSpecification.expect()
.log().body(false) // `shouldPrettyPrint` parameter set to false
但它只影響日志記錄,而不影響實際的響應正文。
關於響應身體的斷言,它是內容類型。 如果某些 API 提供了無效的標頭並且無法在服務器端修復它,您可以在客戶端解決它。 在 RestAssured 的情況下,可以使用過濾器來完成:
static final Filter FORCE_JSON_RESPONSE_BODY = (reqSpec, respSpec, ctx) -> {
Response response = ctx.next(reqSpec, respSpec);
((RestAssuredResponseOptionsImpl) response).setContentType("application/json");
return response;
};
// globally
RestAssured.filters(FORCE_JSON_RESPONSE_BODY);
// or per request
Response response = RestAssured
.given()
.filters(FORCE_JSON_RESPONSE_BODY)
.get("something")
你可以這樣做:
import io.restassured.http.ContentType;
RestAssured.given()
.header("Accept", "application/json")
.when()
.get(endpoint)
.then()
.statusCode(200)
.contentType(ContentType.JSON);
上面的 header 提供了 header 參數。 處理完請求后,它會檢查狀態代碼 200 和 JSON 格式的內容類型。
但是html標簽從何而來?
有人手動添加了它們,或在服務器或客戶端上編寫了一個規則以添加它們。 “內容類型”是標題的一部分。
HTML和BODY是作為文檔一部分的標記標簽。 如果我記得正確的話,那么在HTML5中就沒有必要了。
您有兩種選擇:1)讓添加這些內容的人刪除它們。 (甚至可能是您自己)2)使用“ no-lambda”樣式:“ response =”,從響應中刪除標簽,然后檢查生成的json。 有關詳細信息,請參見https://github.com/rest-assured/rest-assured/wiki/usage#getting-response-data您將需要添加一個步驟,以通過某些字符串操作或html解析器去除html標簽。
根據端點的實現方式,返回的數據格式可能取決於客戶端發送的Accept
標頭的值。 因此,當您使用 Postman 和 RESTAssured 測試進行測試時,請准確檢查您發送的標頭 - 它們可能會有所不同,如果您沒有在請求中明確指定Accept: application/json
,您的端點可能會返回 HTML。
html 標簽來自 Content-Type 為 text/html,因此 json 數據被識別為文本並被包裝在 html 的正文中。 如果您檢查瀏覽器中的文本,您可能會看到 html 標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.