【问题标题】:How to solve error code "405" on API call with testing?如何通过测试解决 API 调用中的错误代码“405”?
【发布时间】:2019-01-10 11:55:51
【问题描述】:

我在 IntelliJ 的运行模式下测试我的 API 调用时收到错误代码“405”。但是,当我测试 API cal 时;在 Postman 中使用相同的参数就可以了。

我正在编写一个点唱机,用户必须登录才能使用它。登录表单有效,当我尝试使用 Postman 登录时,它也会成功登录。但是,当我在 IntelliJ 上运行我的代码时,它给了我错误代码“405”,这意味着“方法不允许”。

我的 userController 类代码有效:

@PostMapping(value = "/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String login(@RequestBody MultiValueMap<String, String> body){
    String email = body.getFirst("email");
    String username = body.getFirst("username");
    String password = body.getFirst("password");

    return userService.loginUser(email, username, password);
}

我的功能测试代码(也有效,因为我的 API 测试中的其他 GET 方法有效):
公共类功能测试 {

@BeforeClass
public static void setup() {
    String port = System.getProperty("server.port");
    if (port == null) {
        RestAssured.port = Integer.valueOf(8080);
    }
    else{
        RestAssured.port = Integer.valueOf(port);
    }


    String basePath = System.getProperty("server.base");
    if(basePath==null){
        basePath = "/";
    }
    RestAssured.basePath = basePath;

    String baseHost = System.getProperty("server.host");
    if(baseHost==null){
        baseHost = "http://localhost";
    }
    RestAssured.baseURI = baseHost;
}
} 

最后是我用于测试登录的 POST 方法的代码:

//User control
@Test
public void checkLogin(){

    given()
            .param("email", "123")
            .param("username", "123")
            .param("password", "123")
            .when()
            .get("/login")
            .then()
            .statusCode(200);
}

希望有人能帮我解决这个问题。

提前致谢!

【问题讨论】:

    标签: java maven api testing rest-assured


    【解决方案1】:

    405 表示方法不允许。发生这种情况是因为您公开了 POST 操作(@PostMapping(value = "/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) 但试图通过 GET 进行消费:.when().get("/login")

    【讨论】:

      猜你喜欢
      • 2014-11-23
      • 2021-12-13
      • 1970-01-01
      • 2023-02-20
      • 2014-10-14
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多