kkkkkkkkkkkk 2022. 3. 31. 11:46

👻  Repository 에 저장된 값을 조회하는 기능을 만들어보자!

controller 클래스에 findById() 기능을 추가해봅시다.

@GetMapping("/api/v1/posts/{id}") -> http get() 사용
public PostsResponseDto findById(@PathVariable Long id) { -> uri 에 있는 변수값을 설정
    return postsService.findById(id);
}

다음으로는 응답을 받아주는 ResponseDto 클래스를 생성해 봅시다.

@Getter
public class PostsResponseDto {

    private final Long id; // id
    private final String title; // 제목
    private final String content; // 제목
    private final String author; // 작성자

    public PostsResponseDto(Posts entity) {
        this.id = entity.getId();
        this.title = entity.getTitle();
        this.content = entity.getContent();
        this.author = entity.getAuthor();
    }
}

ResponseDto 는 Repository 에서 값을 얻어와 전달 해주는 역할을 합니다.

그래서 필드 멤버에 final 키워드를 붙여주어서 변하지 않는 수 라고 정의 해 주었고 entity 클래스와 마찬가지로 setter() 는 사용하지 않아 getter() 만 추가 해 주었습니다.

Service 클래스에 findById() 기능을 추가 해 봅시다.

public PostsResponseDto findById(Long id) {
    Posts entity = postsRepository.findById(id)
                        .orElseThrow(()-> new IllegalArgumentException("존재하는 게시글이 없습니다."));
    return new PostsResponseDto(entity);
}

Respository 의 findById() 의 반환 타입이 Optional 이므로 orElseThrow() 로 조회하는 id 가 없을 때 에외를 던집니다.

조회하는 id 가 있을 경우 ResponsDto 객체에 데이터를 담아 반환 해줍니다.

여기서 다시 한번 언급을 하는데 Service 클래스에서는 비지니스 로직을 처리하는 것이 아니고 domain 클래스에서 비지니스 로직을 처리합니다.!!

🕶  테스트 코드를 작성 해봅시다!

ResponseDto TEST

@SpringBootTest
class PostsResponseDtoTest {

    @Autowired
    PostsRepository repository;

    @BeforeEach
    public void beforeEach() {
        PostsSaveRequestDto requestDto = PostsSaveRequestDto.builder()
                .title("테스트")
                .content("테스트 중 입니다.")
                .author("홍길동")
                .build();

        repository.save(requestDto.toEntity());
    }

    @Test
    @DisplayName("ResponseEntity_TEST")
    void PostsResponseDtoTest() {
        // given
        Long expectId = 1L;
        String expectTitle = "테스트";
        String expectContent = "테스트 중 입니다.";
        String expectAuthor = "홍길동";

        // when
        Posts posts = repository.findById(expectId)
                .orElseThrow(()-> new IllegalArgumentException("존재하지 않아요!!"));

        PostsResponseDto responseDto = new PostsResponseDto(posts);

        // then
        assertThat(responseDto.getId()).isEqualTo(expectId);
        assertThat(responseDto.getTitle()).isEqualTo(expectTitle);
        assertThat(responseDto.getContent()).isEqualTo(expectContent);
        assertThat(responseDto.getAuthor()).isEqualTo(expectAuthor);
    }

}

Service 클래스의 findById() 기능 테스트!

    @Autowired
    PostsService postsService;

    @Autowired
    PostsRepository postsRepository;

    @BeforeEach
    public void beforeEach() {
        PostsSaveRequestDto dto = PostsSaveRequestDto.builder()
                .title("테스트1")
                .content("테스트 중 입니다.1")
                .author("홍길동1")
                .build();

        postsService.save(dto);
    }

    @AfterEach
    public void afterEach() {
        postsRepository.deleteAll();
    }

    @Test
    @DisplayName("FindById_TEST")
    void findById() {
        // given
        Long expectId = 1L;
        String expectTitle = "테스트1";
        String expectContent = "테스트 중 입니다.1";
        String expectAuthor = "홍길동1";

        // when
        PostsResponseDto responseDto = postsService.findById(expectId);

        // then
        assertThat(responseDto.getId()).isEqualTo(expectId);
        assertThat(responseDto.getTitle()).isEqualTo(expectTitle);
        assertThat(responseDto.getContent()).isEqualTo(expectContent);
        assertThat(responseDto.getAuthor()).isEqualTo(expectAuthor);
}

Controller 클래스 findById() 기능 테스트!

@Test
@DisplayName("findByID_조회_TEST")
void findById() {
    // given
    PostsSaveRequestDto requestDto = PostsSaveRequestDto.builder()
                .title("테스트")
                .content("테스트 중 입니다.")
                .author("홍길동")
                .build();

    Posts savedPosts = postsRepository.save(requestDto.toEntity());

    Long findId = 1L;
    String url = "<http://localhost>:" + port + "/api/v1/posts/" + findId;

    HttpEntity<PostsSaveRequestDto>postsSaveRequestDtoHttpEntity =
            new HttpEntity<>(requestDto);

    // when
    ResponseEntity<Posts> responseEntity =
            restTemplate.exchange(url, HttpMethod.GET, postsSaveRequestDtoHttpEntity, Posts.class);

    // then
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(responseEntity.getBody().getTitle()).isEqualTo(requestDto.getTitle());
    assertThat(responseEntity.getBody().getContent()).isEqualTo(requestDto.getContent());
    assertThat(responseEntity.getBody().getAuthor()).isEqualTo(requestDto.getAuthor());
}

Response로 내려진 status 와 body 내용을 검증 하였습니다.