@Entity@Getter@Setter@NoArgsConstructor@AllArgsConstructor@Builderpublic class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long Id; @NotEmpty private String email; @NotEmpty private String name; @NotNull private Long level; public boolean isAdmin() { return level > 2L; } public void deactivate(){ level = 0L; } public boolean isActive() { return level > 0L; }}
@Repositorypublic interface UserRepository extends JpaRepository<User, Long> {}
@Service@RequiredArgsConstructorpublic class UserService { private final UserRepository userRepository; public List<User> getUsers() { return userRepository.findAll(); } public User addUser(String email, String name) { User user = User.builder() .email(email) .name(name) .level(1L) .build(); userRepository.save(user); return user; } public User updateUser(Long id, String email, String name, Long level ) { User user = userRepository.findById(id).orElse(null); user.setEmail(email); user.setName(name); user.setLevel(level); return user; } public User deactivateUser(Long userId) { User user = userRepository.findById(userId).orElse(null); user.deactivate(); return user; }}
class UserServiceTest { @Mock private UserRepository userRepository; private UserService userService; @BeforeEach private void setUp() { MockitoAnnotations.openMocks(this); userService = new UserService(userRepository); } @Test @DisplayName("유저목록을 가져온다.") public void getUsers() { List<User> mockUsers = new ArrayList<>(); mockUsers.add(User.builder() .name("tester") .email("test@example.com") .level(3L) .build()); given(userRepository.findAll()).willReturn(mockUsers); List<User> users = userService.getUsers(); User user = users.get(0); assertThat(user.getName()).isEqualTo("tester"); assertThat(user.getEmail()).isEqualTo("test@example.com"); } @Test @DisplayName("유저를 추가한다.") public void addUser(){ String email = "test@example.com"; String name = "tester"; User mockUser = User.builder() .name(name) .email(email) .build(); given(userRepository.save(any())).willReturn(mockUser); User user = userService.addUser(email, name); assertThat(user.getName()).isEqualTo(name); assertThat(user.getEmail()).isEqualTo(email); } @Test @DisplayName("유저를 업데이트 한다.") public void updateUser(){ Long id = 1004L; Long level = 3L; String email = "test@example.com"; String name = "Superman"; User mockUser = User.builder() .Id(id) .name("Administrator") .level(1L) .email(email) .build(); given(userRepository.findById(id)).willReturn(Optional.of(mockUser)); User user = userService.updateUser(id, email, name, level); verify(userRepository).findById(id); assertThat(user.getName()).isEqualTo("Superman"); assertThat(user.isAdmin()).isEqualTo(true); } @Test @DisplayName("유저를 삭제한다.") public void deactiveUser(){ Long id = 1004L; Long level = 2L; String email = "test@example.com"; String name = "Superman"; User mockUser = User.builder() .Id(id) .level(level) .email(email) .name(name) .build(); given(userRepository.findById(id)).willReturn(Optional.of(mockUser)); User user = userService.deactivateUser(1004L); verify(userRepository).findById(1004L); assertThat(user.isAdmin()).isEqualTo(false); assertThat(user.isActive()).isEqualTo(false); }}
@RestController@RequiredArgsConstructorpublic class UserController { // 1. User list // 2. User create -> 회원가입 // 3. User update // 4. User delete -> level: 0 => 아무것도 못 함. // (1: customer 2: restaurant owner 3: admin) private final UserService userService; @GetMapping("/users") public List<User> list(){ return userService.getUsers(); } @PostMapping("/users") public ResponseEntity<?> create(@RequestBody User resource) throws URISyntaxException { User user = userService.addUser(resource.getEmail(), resource.getName()); String url = "/users" + user.getId(); return ResponseEntity.created(URI.create(url)).body("{}"); } @PatchMapping("/users/{userId}") public void udpate(@PathVariable("userId") Long id, @RequestBody User user){ userService.updateUser(id, user.getEmail(), user.getName(), user.getLevel()); } @DeleteMapping("/users/{userId}") public String deactivate(@PathVariable("userId")Long userId){ userService.deactivateUser(userId); return "{}"; }}
@WebMvcTest(UserController.class)class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test @DisplayName("유저목록을_가져온다") public void list() throws Exception { List<User> users = new ArrayList<>(); users.add(User.builder() .email("tester@example.com") .name("tester") .level(1L) .build()); given(userService.getUsers()).willReturn(users); mockMvc.perform(get("/users")) .andExpect(status().isOk()) .andExpect(content().string(containsString("tester"))); } @Test @DisplayName("유저를 추가한다.") public void create() throws Exception { String email = "admin@example.com"; String name = "Administrator"; User user = User.builder() .email(email) .name(name) .build(); given(userService.addUser(email, name)).willReturn(user); ResultActions resultActions = mockMvc.perform(post("/users") .contentType(MediaType.APPLICATION_JSON) .content("{\"email\" : \"admin@example.com\", \"name\" : \"Administrator\"}")); verify(userService).addUser(email, name) ; resultActions .andExpect(status().isCreated()); } @Test @DisplayName("유저상태를 업데이트 한다") public void update() throws Exception { Long id = 1004L; String email = "admin@example.com"; String name = "Administrator"; Long level = 3L; User user = User.builder() .email(email) .name(name) .level(level) .build(); given(userService.updateUser(id, email, name, level)).willReturn(user); ResultActions resultActions = mockMvc.perform(patch("/users/1004") .contentType(MediaType.APPLICATION_JSON) .content("{\"level\": 3" + ",\"email\" : \"admin@example.com\"" + ", \"name\" : \"Administrator\"}")); verify(userService).updateUser(eq(id), eq(email), eq(name), eq(level)); resultActions .andExpect(status().isOk()); } @Test @DisplayName("유저를 삭제한다.") public void deactivate() throws Exception { mockMvc.perform(delete("/users/1004")) .andExpect(status().isOk()); verify(userService).deactivateUser(1004L); }}