为什么这些 REST Assured 查询无法获得与 Postman 中相同的结果? (403 或 400 状态代码与所需的 201)

问题描述 投票:0回答:1

对于大学的一个小组项目,我们正在编写一个 Micronaut 应用程序,用于使用 REST API 管理一些数据,我应该使用 REST Assured 对其进行测试。首先,我基本上尝试转换一个成功的 Postman 请求(POST 到带有 body

{"name":"Test Device"}
的路径 user/38/devices - 即为这个随机现有用户创建一个名为“测试设备”的设备 - 通过身份验证不记名令牌)到 REST Assured 代码,仅检查状态代码是否应为 201。

在解析 REST Assured 和 Micronaut Test 使用指南后,我的第一次尝试是:

@Test
public void devicePostTest(RequestSpecification spec) {
    spec.given().auth().oauth2(bearerToken).param("name", "Test Device")
            .when().post("/user/38/devices")
            .then().statusCode(201);
}

但是状态码是403。 找到这个类似的 Stackoverflow 问题后,我将其更改为:

@Test
public void devicePostTest(RequestSpecification spec) {
    spec.given().headers("Authorization", "Bearer " + bearerToken,"Content-Type", ContentType.JSON,
                "Accept", ContentType.JSON)
            .param("name", "Test Device")
            .when().post("/user/38/devices")
            .then().statusCode(201);
    }

奇怪的是现在抛出了 400。此时,我发现 Postman 的生成 cURL 的功能给了我这个:

curl --location 'http://localhost:9080/user/38/devices' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer *bearerToken*' \
--data '{
    "name":"Test Device"
}'

因此,我从代码中删除了“Accept”标头,以更紧密地匹配 cURL,但效果并不好。 有趣的是,删除“Content-Type”标头也会导致返回 403 状态代码,无论它告诉我们什么。

也许我在这里错过了一些非常基本的知识(这是我第一次使用除 Java 之外的基本知识),也许我犯了一些明显的错误或完全是其他东西。不管它是什么,我不知道它可能是什么。

java postman rest-assured micronaut micronaut-rest
1个回答
0
投票
  • 首先,
    param()
    用于查询参数或路径参数,如果你想在json中添加body,请使用
    .body()
    代替。
  • 第二,
    ContentType.JSON
    不等于
    appplication/json
    ,它是
    application/json; charest=utf-8

代码为:

spec.given().header("Authorization", "Bearer " + bearerToken)
        .contentType("application/json")
        .body("{\"name\":\"Test Device\"}")
        .when().post("/user/38/devices")
        .then().statusCode(201);
© www.soinside.com 2019 - 2024. All rights reserved.