Initial Commit (#6202)
This commit is contained in:
parent
e67915213a
commit
f3faf9234e
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.validation.application;
|
||||
|
||||
import com.baeldung.validation.application.entities.User;
|
||||
import com.baeldung.validation.application.repositories.UserRepository;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CommandLineRunner run(UserRepository userRepository) throws Exception {
|
||||
return (String[] args) -> {
|
||||
User user1 = new User("Bob", "bob@domain.com");
|
||||
User user2 = new User("Jenny", "jenny@domain.com");
|
||||
userRepository.save(user1);
|
||||
userRepository.save(user2);
|
||||
userRepository.findAll().forEach(System.out::println);
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.validation.application.controllers;
|
||||
|
||||
import com.baeldung.validation.application.entities.User;
|
||||
import com.baeldung.validation.application.repositories.UserRepository;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class UserController {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
public UserController(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@GetMapping("/users")
|
||||
public List<User> getUsers() {
|
||||
return (List<User>) userRepository.findAll();
|
||||
}
|
||||
|
||||
@PostMapping("/users")
|
||||
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
|
||||
return ResponseEntity.ok("User is valid");
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
|
||||
Map<String, String> errors = new HashMap<>();
|
||||
ex.getBindingResult().getAllErrors().forEach((error) -> {
|
||||
String fieldName = ((FieldError) error).getField();
|
||||
String errorMessage = error.getDefaultMessage();
|
||||
errors.put(fieldName, errorMessage);
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.validation.application.entities;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@NotBlank(message = "Name is mandatory")
|
||||
private String name;
|
||||
|
||||
@NotBlank(message = "Email is mandatory")
|
||||
private String email;
|
||||
|
||||
public User(){}
|
||||
|
||||
public User(String name, String email) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.validation.application.repositories;
|
||||
|
||||
import com.baeldung.validation.application.entities.User;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends CrudRepository<User, Long> {}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.validation.tests;
|
||||
|
||||
import com.baeldung.validation.application.controllers.UserController;
|
||||
import com.baeldung.validation.application.repositories.UserRepository;
|
||||
import java.nio.charset.Charset;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.hamcrest.core.Is;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest
|
||||
@AutoConfigureMockMvc
|
||||
public class UserControllerIntegrationTest {
|
||||
|
||||
@MockBean
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
UserController userController;
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void whenUserControllerInjected_thenNotNull() throws Exception {
|
||||
assertThat(userController).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestToUsers_thenCorrectResponse() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/users")
|
||||
.contentType(MediaType.APPLICATION_JSON_UTF8))
|
||||
.andExpect(MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() 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));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue