Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat#50: user 프로필 조회 기능 구현 #51

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/main/java/server/poptato/user/api/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.web.bind.annotation.*;
import server.poptato.global.response.BaseResponse;
import server.poptato.user.api.request.UserChangeNameRequestDto;
import server.poptato.user.application.response.UserResponseDto;
import server.poptato.user.application.service.UserService;
import server.poptato.user.resolver.UserId;

Expand All @@ -27,4 +28,9 @@ public BaseResponse updateUserName(@UserId Long userId, @Validated @RequestBody
userService.updateUserName(userId, request.getNewName());
return new BaseResponse();
}
@GetMapping("/mypage")
public BaseResponse getUserNameAndEmail(@UserId Long userId) {
UserResponseDto response = userService.getUserNameAndEmailById(userId);
return new BaseResponse(response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package server.poptato.user.application.response;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
@AllArgsConstructor
public class UserResponseDto {
private String name;
private String email;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.transaction.annotation.Transactional;
import server.poptato.auth.application.service.JwtService;
import server.poptato.todo.domain.repository.TodoRepository;
import server.poptato.user.application.response.UserResponseDto;
import server.poptato.user.domain.entity.User;
import server.poptato.user.domain.repository.UserRepository;
import server.poptato.user.exception.UserException;
Expand Down Expand Up @@ -35,18 +36,18 @@ public void deleteUser(Long userId) {
entityManager.flush();
}
@Transactional
@CacheEvict(value = "users", key = "#kakaoId")
public Optional<User> findUserByKakaoId(String kakaoId) {
entityManager.clear(); // 영속성 컨텍스트 초기화
return userRepository.findByKakaoId(kakaoId);
}
@Transactional
public void updateUserName(Long userId, String newName) {
// 사용자 조회
User user = userRepository.findById(userId)
.orElseThrow(() -> new UserException(UserExceptionErrorCode.USER_NOT_EXIST));

// name 업데이트
user.changeName(newName);
}
@Transactional(readOnly = true)
public UserResponseDto getUserNameAndEmailById(Long userId) {
User user = userRepository.findById(userId)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

User user = userRepository.findById(userId)
.orElseThrow(() -> new UserException(UserExceptionErrorCode.USER_NOT_EXIST));
이 부분이 서비스 메서드마다 있는데, 하나의 메소드로 리팩토링해보는 건 어떨까요?

.orElseThrow(() -> new UserException(UserExceptionErrorCode.USER_NOT_EXIST));

return new UserResponseDto(user.getName(), user.getEmail());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Response는 만들어놓은 Builder를 사용해도 될 것 같아요!

}
}
21 changes: 21 additions & 0 deletions src/test/java/server/poptato/user/api/UserControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
Expand Down Expand Up @@ -53,6 +54,26 @@ class UserControllerTest {
void 액세스토큰_비활성화() {
jwtService.deleteRefreshToken(userId);
}

@Test
@DisplayName("프로필 조회 성공 테스트")
void getUserNameAndEmail() throws Exception {
mockMvc.perform(get("/user/mypage")
.header("Authorization", "Bearer "+accessToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
@Test
@DisplayName("프로필 조회 실패 테스트 - invalid token")
void getUserNameAndEmailFailedInvalidToken() throws Exception {
String invalidToken = "invalidToken";
mockMvc.perform(get("/user/mypage")
.header("Authorization", "Bearer "+invalidToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andDo(print());
}
@Test
@DisplayName("사용자 이름 변경 성공 테스트")
void updateUserName_ShouldReturnSuccess() throws Exception {
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/server/poptato/user/application/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import server.poptato.user.application.response.UserResponseDto;
import server.poptato.user.application.service.UserService;
import server.poptato.user.domain.entity.User;
import server.poptato.user.domain.repository.UserRepository;
Expand Down Expand Up @@ -54,5 +55,29 @@ void updateUserName_ShouldThrowException_WhenUserNotFound() {

assertThat(exception.getMessage()).isEqualTo(UserExceptionErrorCode.USER_NOT_EXIST.getMessage());
}
@Test
@DisplayName("getUserNameAndEmailById 메서드는 유효한 userId가 주어졌을 때 사용자 이름과 이메일을 반환한다")
public void shouldReturnUserNameAndEmail_WhenUserIdIsValid() {
// Given
Long userId = 1L;

// When
UserResponseDto responseDto = userService.getUserNameAndEmailById(userId);

// Then
assertThat(responseDto.getName()).isEqualTo("Poptato");
assertThat(responseDto.getEmail()).isEqualTo("[email protected]");
}

@Test
@DisplayName("getUserNameAndEmailById 메서드는 유효하지 않은 userId가 주어졌을 때 UserException을 던진다")
public void shouldThrowUserException_WhenUserIdIsInvalid() {
// Given
Long invalidUserId = 2L;

// When & Then
org.junit.jupiter.api.Assertions.assertThrows(UserException.class,
() -> userService.getUserNameAndEmailById(invalidUserId));
}
}