spring api
https://spring.io/guides/tutorials/rest/
https://www.baeldung.com/spring-boot-bean-validation
Test Code
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception { MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8")); String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}"; mockMvc.perform(MockMvcRequestBuilders.post("/users") .content(user) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content() .contentType(textPlainUtf8)); } public void whenPostRequestToUsersAndInValidUser_thenCorrectResponse() throws Exception { String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}"; mockMvc.perform(MockMvcRequestBuilders.post("/users") .content(user) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory"))) .andExpect(MockMvcResultMatchers.content() .contentType(MediaType.APPLICATION_JSON_UTF8)); } }
Mock Mvc
Data validation
- GUI - Client Data validation
- Application Services - Application Data Validation
- Database - Database Data Validation
Reference
- Jakarta (Java) Bean Validation Home page
- Hibernate Validator Home page
- Java Bean Validation Annotations API Docs Reference
Related REST API Tutorials:
- Spring Boot REST API Validate Path Variables Examples
- Spring Boot REST API Validate Query Parameters Examples
- REST API Best Practices: How to Use the Right HTTP Methods and Status Codes
- How to Use curl for Testing REST APIs (Test CRUD Operations)
- Java RESTful Web Services Tutorial for Beginner with Jersey and Tomcat
- Java CRUD RESTful Web Services Examples with Jersey and Tomcat
- Spring Boot Hello World RESTful Web Services Tutorial
- Spring Boot RESTful CRUD API Examples with MySQL database
- Spring Boot File Download and Upload REST API Examples
- Spring Boot REST API CRUD with HATEOAS Tutorial
댓글
댓글 쓰기