簡體   English   中英

使用Java RestAssured創建POST請求,返回狀態碼422

[英]Create POST request, using Java RestAssured, returns status code 422

我在Windows 10上有Ubuntu服務器實例。我有在Ubuntu上的localhost上運行的應用程序。 在Ubuntu終端上創建請求時:

curl http://localhost:8000/test \
    -H "Content-Type: application/json;charset=UTF-8" \
    -H "Authorization: Basic cJJdlJ26p62JG23j34==" \
    -d '{
    "test": {
      "id": "564624232443234",
      "type": "book"
    }
}'

它可以工作並插入數據庫。

當我在Eclipse中使用上述相同的JSON值進行JUnit測試時:

public class Test extends Connection {
.......

    @Test
    public void test_Insert() {
        Map<Object, String> mapRequest = new HashMap<>();
        mapRequest.put("id", "564624232443234");
        mapRequest.put("type", "book");

        given().
            contentType(ContentType.JSON).  
            header("Authorization", "Basic "+"cJJdlJ26p62JG23j34==").
            body(mapRequest).
        when().
            post("test").
        then().
            statusCode(200);

    }

沒用 返回我:

java.lang.AssertionError:1個期望失敗。 預期狀態碼為<200>,但為<422>。

如果僅按如下所示ping服務器,則響應是正確的(200)。

    @Test
    public void basicPingTest() {
        given().when().get("/").then().statusCode(200);
    }

對這個問題有什么想法嗎? 謝謝

您不會通過curl和RestAssured發送相同的請求。 卷曲:

{
    "test": {
        "id": "564624232443234",
        "type": "book"
    }
}

放心:

{
    "id": "564624232443234",
    "type": "book"
}

將地圖添加為test對象

public class Test extends Connection {
.......

    @Test
    public void test_Insert() {
        Map<Object, String> mapRequest = new HashMap<>();
        mapRequest.put("id", "564624232443234");
        mapRequest.put("type", "book");

        given().
            contentType(ContentType.JSON).  
            header("Authorization", "Basic "+"cJJdlJ26p62JG23j34==").
            body(Collections.singletonMap("test",mapRequest)).
        when().
            post("test").
        then().
            statusCode(200);

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM