728x90
이전글
첫 번째 미션
AWS EC2에 Docker 배포Gitlab CI & Crontab CDSwagger회원가입로그인포스트 작성, 수정, 삭제, 리스트
추가
JWT Exception- Test Code 작성
Test Code
User
UserController Test
...
class UserControllerTest {
...
/* 로그인 */
@Test
@DisplayName("로그인 성공")
void login_success() throws Exception {
UserDto userDto = UserDto.builder()
.id(1)
.userName("jun")
.password("abcd")
.userRole(UserRole.USER)
.build();
UserLoginRequest request = new UserLoginRequest(userDto.getUserName(), userDto.getPassword());
UserLoginResponse response = new UserLoginResponse(token);
given(userService.login(any())).willReturn(response);
String url = "/api/v1/users/login";
mockMvc.perform(post(url).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(request)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.resultCode").exists())
.andExpect(jsonPath("$.resultCode").value("SUCCESS"))
.andExpect(jsonPath("$.result.jwt").exists())
.andExpect(jsonPath("$.result.jwt").value(token))
.andDo(print());
verify(userService, times(1)).login(any());
}
}
...
class UserControllerTest {
...
/* 로그인 */
...
@Test
@DisplayName("로그인 실패_userName 없음")
void login_fail_empty_user_name() throws Exception {
UserDto userDto = UserDto.builder()
.id(1)
.userName("jun")
.password("abcd")
.userRole(UserRole.USER)
.build();
UserLoginRequest request = new UserLoginRequest("abc", "bbcd");
given(userService.login(any()))
.willThrow(new SNSAppException(USERNAME_NOT_FOUND, USERNAME_NOT_FOUND.getMessage()));
String url = "/api/v1/users/login";
mockMvc.perform(post(url).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(request)))
.andExpect(status().isNotFound())
.andDo(print());
}
}
Post
PostController Test
...
class PostControllerTest {
...
/* 포스트 상세 */
@Test
@DisplayName("포스트 상세 보기")
void post_one_detail() throws Exception {
Post dto = PostFixture.get();
int postId = dto.getId();
PostReadResponse response = PostReadResponse.builder()
.id(dto.getId())
.title(dto.getTitle())
.body(dto.getBody())
.userName(dto.getUser().getUserName())
.createdAt(time)
.lastModifiedAt(time)
.build();
given(postService.getPost(any())).willReturn(response);
String url = String.format("/api/v1/posts/%d", postId);
mockMvc.perform(get(url).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(dto)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.resultCode").exists())
.andExpect(jsonPath("$.resultCode").value("SUCCESS"))
.andExpect(jsonPath("$.result.id").exists())
.andExpect(jsonPath("$.result.id").value(1))
.andExpect(jsonPath("$.result.title").exists())
.andExpect(jsonPath("$.result.title").value("제목"))
.andExpect(jsonPath("$.result.body").exists())
.andExpect(jsonPath("$.result.body").value("내용"))
.andExpect(jsonPath("$.result.userName").exists())
.andExpect(jsonPath("$.result.userName").value("chordpli"))
.andExpect(jsonPath("$.result.createdAt").exists())
.andExpect(jsonPath("$.result.lastModifiedAt").exists())
.andDo(print());
verify(postService, times(1)).getPost(any());
}
}
...
class PostControllerTest {
...
@Test
@DisplayName("포스트 작성 실패")
void post_fail_no_token() throws Exception {
PostRequest request = new PostRequest("title", "content");
given(postService.post(any(), any())).willThrow(new SNSAppException(INVALID_PERMISSION, "토큰이 존재하지 않습니다."));
String url = "/api/v1/posts";
mockMvc.perform(post(url).with(csrf())
.header(HttpHeaders.AUTHORIZATION, "")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(request)))
.andExpect(status().isUnauthorized())
.andDo(print());
verify(postService, times(1)).post(any(), any());
}
}
PostService Test
class PostServiceTest {
...
/* 포스트 상세 */
@Test
@DisplayName("조회 성공")
void success_get_post() {
Post fixture = PostFixture.get();
when(postRepository.findById(any())).thenReturn(Optional.of(fixture));
PostReadResponse response = postService.getPost(fixture.getId());
assertEquals(fixture.getUser().getUserName(), response.getUserName());
}
}
class PostServiceTest {
...
/* 포스트 삭제 */
@Test
@DisplayName("삭제 실패_유저가 존재하지 않음")
void fail_delete_post_not_exist_user() {
Post fixture = PostFixture.get();
when(userRepository.findByUserName(any())).thenReturn(Optional.empty());
SNSAppException exception
= Assertions.assertThrows(SNSAppException.class,
() -> postService.deletePost(fixture.getId(), fixture.getUser().getUserName()));
Assertions.assertEquals(ErrorCode.USERNAME_NOT_FOUND, exception.getErrorCode());
}
}
다음글
반응형
'회고록 > Archive' 카테고리의 다른 글
[Project] 08. SNS 웹 서비스 제작 (1) | 2023.01.04 |
---|---|
[Project] 07. SNS 웹 서비스 제작 (1) | 2022.12.29 |
[Project] 05. SNS 웹 서비스 제작 (0) | 2022.12.26 |
[Project] 04. SNS 웹 서비스 제작 (0) | 2022.12.23 |
[Project] 03. SNS 웹 서비스 제작 (0) | 2022.12.23 |