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

Create POST request, using Java RestAssured, returns status code 422

我在 Windows 10 上有 Ubuntu 服务器实例。我有应用程序,它在 Ubuntu 上的本地主机上 运行。 当我在 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);

    }

没用。 Returns我:

java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <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);

    }
}