xibrian
xibrian

Reputation: 105

How to test reuqestmethod.get with object parameter by using mockmvc

if I have get method define as below

@GetMapping(value = "/getfood")

public Food getFood(@valid final Order order)

how can i pass Order object in mockmvc test with following code

this.mockMvc.perform(get("/getfood"))

Thanks

Upvotes: 1

Views: 411

Answers (2)

osmingo
osmingo

Reputation: 1064

For sending a custom object in the get request with mockmvc I found this code useful:

Order myOrder = new Order();
mockMvc.perform(
             MockMvcRequestBuilders.get(API_V_1).contentType(APPLICATION_FORM_URLENCODED)
                    .flashAttr("order", myOrder );

Upvotes: 0

ibercode
ibercode

Reputation: 1373

You could use RequestBuilder and MvcResult:

RequestBuilder request = MockMvcRequestBuilders.get("/getfood").accept(MediaType.HTML);

MvcResult result = mockMvc.perform(request).andReturn();

CustomResponse customResponse = new CustomResponse("your data");

ResponseEntity response = new ResponseEntity<CustomResponse>(customResponse, HttpStatus.OK);

assertEquals(response.getBody().toString(), response.getResponse().getContentAsString());

You will need to adapt this example to your code. CustomResponse is a class that you will need to create. The rest are imports from org.springframework.test.web.servlet.*

Upvotes: 1

Related Questions