1

I have a controller that contains 2+ methods:

@RequestMapping(method = RequestMethod.GET, value = "/{uuid}", produces = "application/json")
public MyObject findByUuid(
        @PathVariable("uuid") String uuid) {
    ...
}

@RequestMapping(method = RequestMethod.POST, value = "/findByStringPropertyEquals", produces = "application/json")
public List<MyObject> findByStringPropertyEquals(
            @RequestParam("type") String type,
            @RequestParam("property") String property,
            @RequestParam("value") String value) {
    ...
}

Now when I try to test the second method like

 mvc.perform(get("/findByStringPropertyEquals?type={0}&property={1}&value={2}", "Person", "testPropInt", 42))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(1)));

then MockMvc picks up the findByUuid controller method unfortunately. Output is

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/v1/domain-entities/findByStringPropertyEquals
       Parameters = {type=[Person], property=[testPropInt], value=[42]}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.example.MyObjectController
           Method = public com.example.MyObject com.example.MyObjectController.findByUuid(java.lang.String)

However, accessing the REST API regularly when the web server is started is working fine. Is that a bug or do I do something wrong?

Steffen Harbich
  • 2,639
  • 2
  • 37
  • 71
  • In your code you are invoking a GET: `mvc.perform(get(...))` however the `findByStringPropertyEquals` method is declared for `POST` so your code cannot address that method with a GET. I'm not sure why the MockMVC layer has chosen `findByUuid` (perhaps because that is the only `GET` method on this controller) but the reason your code is not hitting `findByStringPropertyEquals` is that you have chosen the wrong HTTP method ... try `mvc.perform(post(...))` instead. – glytching Apr 09 '18 at 11:45
  • @glytching That was the problem. Thank you :) ... if you post it as answer I can accept it. – Steffen Harbich Apr 09 '18 at 11:55

1 Answers1

1

In your code you are invoking a GET:

mvc.perform(get("/findByStringPropertyEquals?type={0}&property={1}&value={2}", "Person", "testPropInt", 42))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(1)));

However the findByStringPropertyEquals method is declared for POST so your code cannot address that method with a GET. I'm not sure why the MockMVC layer has chosen findByUuid (perhaps because that is the only GET method on this controller) but the reason your code is not hitting findByStringPropertyEquals is that you have chosen the wrong HTTP method.

Try mvc.perform(post(...)) instead.

glytching
  • 44,936
  • 9
  • 114
  • 120