2

With Spring Boot, I want to test my @RestController, everything is good except when I try to test a request mapping with @PathParam.

This involve the interface (in this case TestController) holding the annotation for request mapping ! If I remove the interface all is good ... Seemes to be an issue ...

My Controller :

public interface TestController {

    @RequestMapping(value = "/bar/{foo}/baz", method = RequestMethod.GET)
    String test(@PathVariable("foo") String foo);


    @RestController
    class TestControllerImpl implements TestController {

        @Override
        public String test(String foo) {
            return foo;
        }
    }

}

My Tests :

@Test
public void notworkingtest() throws Exception {

    //THIS TEST SHOULD WORK, BUT DON'T ...

    final MockMvc mockMvc = ...

    mockMvc.perform(get("/bar/{foo}/baz", "foovalue") // Or get("/bar/foovalue/baz")
            .contentType("text/plain"))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().string("foovalue"));

}

@Test
public void strangeworkingtest() throws Exception {

    //THIS TEST WORKS, BUT WHY ?!?

    final MockMvc mockMvc = ...

    mockMvc.perform(get("/bar/{foo}/baz", "WhatEverValue")
            .param("foo", "foovalue") // This param should be useless ...
            .contentType("text/plain"))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().string("foovalue"));

}

The second test is working when I had .param("foo","foovalue) and keep the get("/bar/{foo}/baz", "WhatEverValue") ...

If I remove the interface of the Controller it works ...

Can someone explain to me ?

Thx

Oziris
  • 176
  • 1
  • 7

3 Answers3

2

Here is two ways:

  1. Change the URL for your endpoint:

    @RequestMapping(value = "/test", method = RequestMethod.GET)

    mockMvc.perform(get("/test") .param("foo", "Value")) .andExpect(status().is2xxSuccessful()) .andExpect(content().string("foovalue"));

  2. Use proper URL to call your endpoint:

    mockMvc.perform(get(" /user/1568/delete")) .andExpect(status().is2xxSuccessful()) .andExpect(content().string("foovalue"));

Speise
  • 757
  • 1
  • 11
  • 25
0

You could try this:

mockMvc.perform(get("/test/{foo}?foo=" + "foovalue")
        .contentType("text/plain"))
        .andExpect(status().is2xxSuccessful())
        .andExpect(content().string("foovalue"));
Hu.Yikang
  • 11
  • 2
0

PathVariable differs from requestParam as pathVariable is part of URL. that's why .param("foo", "foovalue") is not overriding your pathVariable as the latter one is setting a requestParam.

see @RequestParam vs @PathVariable

Thomas.L
  • 246
  • 1
  • 6