Я только начинаю изучать Spring.
Контроллер принимает и возвращает Json. Я не могу это проверить.
Контроллер
@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());
}
}
При тестировании я всегда получить 404. Но если я отправлю запрос от Почтальона, ответ будет 200. Я изучил этот ответ, но он не помог Как проверить JSON ответ весной MVC тест
Результаты испытаний
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