【问题标题】:Create POST request, using Java RestAssured, returns status code 422创建 POST 请求,使用 Java RestAssured,返回状态码 422
【发布时间】:2019-11-24 20:17:39
【问题描述】:

我在 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 期望失败。 预期状态代码 但为 。

如果我只像下面这样 ping 服务器,则响应是正确的 (200)。

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

对这个问题有任何想法吗? 谢谢

【问题讨论】:

    标签: java junit rest-assured


    【解决方案1】:

    您不会通过 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);
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2016-04-09
      • 2015-07-19
      • 2020-11-20
      • 1970-01-01
      相关资源
      最近更新 更多