简体   繁体   English

使用Java RestAssured创建POST请求,返回状态码422

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

I have Ubuntu server instance on Windows 10. I have application, which is running on localhost on Ubuntu. 我在Windows 10上有Ubuntu服务器实例。我有在Ubuntu上的localhost上运行的应用程序。 When I create request on Ubuntu terminal: 在Ubuntu终端上创建请求时:

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

It works and insert into database. 它可以工作并插入数据库。

When I have JUnit test in Eclipse with same JSON values above: 当我在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);

    }

It doesn't work. 没用 Returns me: 返回我:

java.lang.AssertionError: 1 expectation failed. java.lang.AssertionError:1个期望失败。 Expected status code <200> but was <422>. 预期状态码为<200>,但为<422>。

If I only ping the server like below, the response is correct (200). 如果仅按如下所示ping服务器,则响应是正确的(200)。

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

Any ideas of the problem? 对这个问题有什么想法吗? Thanks 谢谢

You don't send the same request by curl and by RestAssured. 您不会通过curl和RestAssured发送相同的请求。 Curl: 卷曲:

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

Restassured: 放心:

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

Add the map as test object 将地图添加为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