简体   繁体   中英

How to solve error code “405” on API call with testing?

I'm getting error code "405" while testing my API calls on run mode in IntelliJ. However when I test the API cal; with the same parameters in Postman it works.

I'm programming a jukebox where an user has to log in in order to use it. The login form works and when i try to log in with Postman it also logs in succesfull. However when i run my code on IntelliJ it gives me error code "405", which means "Method not allowed".

My userController class code which works:

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

My functional testing code(also works because my other GET methods in my API tests works):
public class FunctionalTest {

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

And finally my code for testing the POST method for logging in:

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

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

Hope anyone can help me solve this problem.

Thanks in advance!

405 means method not allowed. This is happening because you are exposing a POST operation ( @PostMapping(value = "/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) but trying to consume by means of a GET : .when().get("/login")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM