Search code examples
javaspringrestfunctional-testing

How to pass a query/path param in functional/unit test?


I want to write a test for my controller. And I need to pass a parameter to get(). How can I do it?

Controller:

@GetMapping("/getClientById")
    public ModelAndView getClientById(Integer id){
        return new ModelAndView("getClientById", "client", clientService.getClientById(id));
    }

Test method:

given().header("Content-Type", "application/x-www-form-urlencoded")
                .when()
                .get("getClientById/")//How can I put here an ID ?
                .then()
                .statusCode(200);

Solution

  • You must include param in your mapping

    @GetMapping("/getClientById/:clientId")
        public ModelAndView getClientById(@PathParam("clientId") Integer id){
    

    or

    @GetMapping("/getClientById")
        public ModelAndView getClientById(@QueryParam("id") Integer id){
    

    and then respectively

    .get("getClientById/youridvalue")//How can I put here an ID ?
    

    and

    .get("getClientById?id=youridvalue")//How can I put here an ID ?
    

    as for second option im think there is a method to include query params but I have no clue what API are you using so cannot elaborate on that (probably not yet)