저번에는 service 코드의 test 코드를 작성했다. 이번에는 repository 코드 안에 메서드가 잘 작동하는지 test 하는 코드를 작성해보도록 한다.
< 기존 Repository 코드>
native query method
:native query method
는 직접 작성한 SQL 쿼리를 .sql 문서나 DB 콘솔이 아니라 리퍼지터리 메서드에서 메서드로 실행할 수 있는 방법이다. 방법은@Query
어노테이션을 사용하거나orm.xml
파일을 이용하는 방법이 있는데 이는 다음에...
저번 service 테스트 코드 디렉터리 위치와 같은 위치에 repository 디렉터리를 생성하고, test 파일을 생성한다.
@DataJpaTest
class CommentRepositoryTest {
@Autowired
CommentRepository commentRepository;
@Test
@DisplayName("특정 게시글의 모든 댓글 조회")
void findByArticleId() {
}
@Test
@DisplayName("특정 닉네임의 모든 댓글 조회")
void findByNickname() {
}
기본 뼈대는 위와 같으며 service test code 와 매우 흡사하다.
@DataJpaTest
: 해당 클래스를 JPA와 연동해 테스팅 - service 코드에서는 @SpringbootTest였으나 JPA와 연동해서 테스트를 진행해야하므로 다른 어노테이션을 사용한다.
@Display()
: 메서드 명을 수정하지 않고 테스트의 이름을 보여주는 어노테이션이다. 메서드 이름은 그대로 둔 채, 이름을 바꾸고 싶을 때 사용한다.
@Test
@DisplayName("특정 게시글의 모든 댓글 조회")
void findByArticleId() {
// 입력 데이터 준비
// 실제 데이터
// 예상 데이터
//비교 및 검증
}
service 테스트 코드와 순서가 조금 다르다. 입력 데이터를 준비함으로써 순차적으로 코드를 작성할 수 있지만 이건 취향차이
//입력 데이터 준비
Long articleId = 4L;
//실제 데이터
List<Comment> comments = commentRepository.findByArticleId(articleId);
//예상 데이터
Article article = new Article(4L, "당신의 인생 영화는?", "댓글로 써주세요");
Comment a = new Comment(1L, article, "Park", "굿 월 헌팅");
Comment b = new Comment(2L, article, "Shim", "아이 앰 샘");
Comment c = new Comment(3L, article, "KIM", "쇼생크 탈출");
List<Comment> expected = Arrays.asList(a, b, c);
//비교 및 검증
assertEquals(expected.toString(), comments.toString(), "4번 글의 모든 댓글을 출력!");
<예상 데이터>
(부모객체 생성)
Article article = new Article(4L, "당신의 인생 영화는?", "댓글로 써주세요");
(댓글 객체 생성)
Comment a = new Comment(1L, article, "Park", "굿 월 헌팅");
Comment b = new Comment(2L, article, "Shim", "아이 앰 샘");
Comment c = new Comment(3L, article, "KIM", "쇼생크 탈출");
(댓글 객체 합치기)
@Test
@DisplayName("특정 닉네임의 모든 댓글 조회")
void findByNickname() {
{
// 입력 데이터 준비
String nickname = "Park";
//실제 데이터
List<Comment> comments = commentRepository.findByNickname(nickname);
//예상 데이터
Comment a = new Comment(1L, new Article(4L,"당신의 인생 영화는?", "댓글로 써주세요"), nickname, "굿 월 헌팅");
Comment b = new Comment(4L, new Article(5L,"당신의 소울 푸드는?", "댓글로 써주세요오옹"),nickname, "치킨");
Comment c = new Comment(7L, new Article(6L,"당신의 취미는?", "댓글로 써주세요이이잉"),nickname, "기타");
List<Comment> expected = Arrays.asList(a, b, c);
//비교 및 검증
assertEquals(expected.toString(), comments.toString(), "Park의 모든 댓글을 출력!");
}
}