InconsistentHashing
InconsistentHashing

Reputation: 311

Spring Restcontroller/MockMvc Issue with Integer input

Apparently I have situation where client wants to pass an integer value to one of the REST endpoint. It does look like

@PostMapping("/handleSignal")
public ResponseEntity<Object> handleSignal(@RequestParam @NotNull Integer signalId)

I have used @RequestParam and tested it successfully with Postman. However, while testing with Spring MockMvc I have not found any way to pass an Integer value. My attempts so far is

RequestBuilder handleSignalRequest = MockMvcRequestBuilders.post("/handleSignal") .requestAttr("signalId", 1); mockMvc.perform(handleSignalRequest) .andExpect(MockMvcResultMatchers.status().isOk());

But this won't hit the endpoint and giving me 400/Bad Request.

I am aware that if I change the method signature to

@PostMapping("/handleSignal")
public ResponseEntity<Object> findSignal(@RequestAttribute(name = "signalId") @NotNull Integer signalId)

Then the testing using MockMvc will go through ( tried it). But in that case I will loose the ability to test it via Postman.

What would be the ideal solution so as to be able to test it both via Postman and Spring MockMvc ? Any lead is appreciated.

Upvotes: 1

Views: 364

Answers (1)

dariosicily
dariosicily

Reputation: 4582

RequestBuilder handleSignalRequest = MockMvcRequestBuilders.post("/handleSignal") .requestAttr("signalId", 1); mockMvc.perform(handleSignalRequest) .andExpect(MockMvcResultMatchers.status().isOk());

You are using the MockHttpServletRequestBuilder#requestAttr wrong method that, as its name says, sets a request attribute while you are interested to send your http post query with the signalid parameter like you do with postman. To achieve the expected result you can use the MockHttpServletRequestBuilder#param method so your request parameter will be parsed from the query string like below with the expected behaviour in your provided test:

RequestBuilder handleSignalRequest = 
               MockMvcRequestBuilders.post("/handleSignal")
                                     .param("signalId", "1");

Upvotes: 1

Related Questions