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
4
  • 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 ? Commented Aug 5, 2020 at 9: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. Commented Aug 5, 2020 at 9:36
  • Added code. The common prefix is only for the application /sb. If you send a request from Postman, the controller works correctly Commented Aug 5, 2020 at 10:08
  • M. Deinum, I corrected the code, but the result is the same Commented Aug 5, 2020 at 10:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

11 Comments

added using Gson to automatically convert object to JSON. Result is the same
please see my updated answer and let me know if it helps
added annotations to @Postmapping for the test. The test does not pass, the result is attached
It wasn’t about the annotations it was about using an object and not a String as a parameter. Also can you update the code so I can see how it looks now.
Edited controller, method saveOrder. Removed all of the business logic. An object is received and returned. It's supposed to work? From Postman post-query works. Иге the test does not pass
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.