0

I'm just starting to learn Spring.

The controller accepts and returns Json. I can't test it.

Controller

     @RestController
        @RequestMapping("/service")
        @Slf4j
        public class OrderController {
            private final OrderService orderService;
            private final ConvertService convertService;
        
            @Autowired
            public OrderController(OrderService orderService, ConvertService convertService) {
                this.orderService = orderService;
                this.convertService = convertService;
            }
        
            @GetMapping
            public String getOrderList(@RequestBody String json) {
                String customer = convertService.toOrder(json).getCustomer();
                List<Order> orderList = orderService.findOrderListByCustomer(customer);
                return convertService.toJson(orderList);
            }
        
            @PostMapping
        @ResponseBody
        @ResponseStatus(HttpStatus.OK)
public String saveOrder(@RequestBody OrderDTO orderDTO) throws JsonProcessingException {

        return objectMapper.writeValueAsString(orderDTO)
            }
        
        }

ControllerTest

  @SpringBootTest
@AutoConfigureMockMvc
class OrderControllerTest {

    @Autowired
    private MockMvc mvc;

    private String json;

    @BeforeEach
    public void setData() {
        json = new Gson().toJson(new OrderDTO ("user1",23));
    }

    @Test
    void getJsonTest() throws Exception {

        mvc.perform(MockMvcRequestBuilders
                .get("/sb/service")
                .header("Accept","application/json")
                .contentType(MediaType.APPLICATION_JSON).content(json))
                .andExpect(status().isOk());
    }

     @Test
void postJsonTest() throws Exception {


    mvc.perform(MockMvcRequestBuilders
            .post("/sb/service")
            .header("Accept","application/json")
            .contentType(MediaType.APPLICATION_JSON).content(json))

            .andExpect(status().isOk());

}

}

When testing, I always get 404. But if I send a request from Postman, the response is 200. I studied this answer, but it didn't help How to check JSON response in Spring MVC test

TestResults

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /sb/service
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"30"]
             Body = {"customer":"user1","cost":23}
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


java.lang.AssertionError: Status expected:<200> but was:<404>
Expected :200
Actual   :404
  • Welcome to SO! Can you share your code where you've set up your mockMvc? Does the path really match? Are there some general prefixes to your Controller Paths like `api/v1` for example or does it really map down to `/sb/service` ? – tpschmidt Aug 05 '20 at 09:06
  • You aren't including the accept header. Also why manually convert to/from String? Spring will do all that for you, not sure why you need the manual conversion (looks like you are working around than rather with the framework). If adding the header doesn't help please add the full test case and not only the test method. – M. Deinum Aug 05 '20 at 09:36
  • Added code. The common prefix is only for the application /sb. If you send a request from Postman, the controller works correctly – Andrew Zhulanov Aug 05 '20 at 10:08
  • M. Deinum, I corrected the code, but the result is the same – Andrew Zhulanov Aug 05 '20 at 10:22

1 Answers1

0

It might also be because of your Controller method accepting a Spring instead of an Object, you can let Spring take care of it

My controller looks like this

@PostMapping
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public String processOrder(@RequestBody OrderDTO orderDTO)

As long as your object (orderDTO in my case) has all the fields (with same name) as in your json, and all the getters, setters and allArgsConstructor it should work

J Asgarov
  • 2,526
  • 1
  • 8
  • 18