게시글 단건 조회
게시글을 저장하는 CRUD 의 C 는 했으니 이젠 R 차례다. 간단하게 게시글 하나를 조회하는 API 를 만들어보자.
PostController
우선 @PathVariable 로 URL 에 글 id 값을 넣어서 서비스로 전달한다.
@GetMapping("/posts/{postId}")
public Post get(@PathVariable(name = "postId") Long id) {
return postService.get(id);
}
PostService
컨트롤러에서 전달받은 id 로 의존성 주입 받은 JpaRepository 구현체의 findById() 메서드를 이용한다.
이 때, Optional 로 감싼 데이터를 응답받는데 이런 데이터는 Optional 을 벗겨주는게 좋다.
public Optional<Post> get(Long id) {
Optional<Post> post = postRepository.findById();
return post;
}
아래처럼 Optional 을 벗긴 뒤 만약 찾는 글이 없다면 예외를 던진다.
public Post get(Long id) {
Post post = postRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 글입니다.")
);
return post;
}
PostServiceTest
해당하는 id 를 가진 글을 조회하고 그 정보를 확인하는 테스트이다.
@SpringBootTest
class PostServiceTest {
@Autowired
private PostService postService;
@Autowired
private PostRepository postRepository;
@BeforeEach
void clean() {
postRepository.deleteAll();
}
@DisplayName("글 단건 조회")
@Test
void get() {
// given
Post requestPost = Post.builder()
.title("우리 이쁜 미카공주님")
.content("우리 공주님")
.build();
Post save = postRepository.save(requestPost);
// when
Post post = postService.get(requestPost.getId());
// then
assertNotNull(post);
assertEquals("우리 이쁜 미카공주님", post.getTitle());
assertEquals("우리 공주님", post.getContent());
}
}
테스트를 수행하면 우리가 원하는대로 동작하며 테스트가 성공함을 확인할 수 있다.
PostControllerTest
요청 값에 해당하는 id 로 조회하고 응답값을 확인하는 테스트이다.
@DisplayName("글 단건 조회")
@Test
void get() throws Exception {
// given
Post post = Post.builder()
.title("우리 이쁜 미카공주님")
.content("우리 공주님")
.build();
postRepository.save(post);
// expected
mockMvc.perform(
MockMvcRequestBuilders.get("/posts/{postId}",post.getId())
.contentType(APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(post.getId()))
.andExpect(jsonPath("$.title").value("우리 이쁜 미카공주님"))
.andExpect(jsonPath("$.content").value("우리 공주님"))
.andDo(print());
}
테스트를 수행하면 원하는대로 동작하며 테스트가 성공함을 확인할 수 있다.
'API 만들어 보기 > 게시판 API' 카테고리의 다른 글
[게시글 조회] 게시글 여러개 조회 (0) | 2023.09.24 |
---|---|
[게시글 조회] 리팩토링 2 (0) | 2023.09.23 |
[작성글 저장] 리팩토링 1 (0) | 2023.09.23 |
[작성글 저장] 게시글 저장 구현 (1) | 2023.09.22 |
[데이터 검증] @ControllerAdvice (0) | 2023.09.22 |