gpt4 book ai didi

java - 如何通过测试解决 API 调用错误代码 "405"?

转载 作者:行者123 更新时间:2023-11-28 21:19:14 24 4
gpt4 key购买 nike

我在 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 方法有效):
公共(public)类功能测试{

@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);
}

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

提前致谢!

最佳答案

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

关于java - 如何通过测试解决 API 调用错误代码 "405"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54128148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com