13일차 - 테스트 코드 작성하기

2024. 8. 16. 13:29코딩 자율학습 스프링 부트3 자바 백엔드 개발 입문 스터디

테스트란

테스트란 프로그램의 품질을 검증하는 것으로, 의도대로 프로그램이 잘 동작하는지 확인하는 과정이다.

테스트 코드 작성법

  1. 예상 데이터 작성하기
  2. 실제 데이터 획득하기
  3. 예상 데이터와 실제 데이터 비교해 검증하기

테스트 케이스

테스트는 다양한 경우를 대비해 작성하는데, 이를 테스트 케이스라고 한다. 성공할 경우, 실패할 경우를 고려하여 작성한다.

테스트 코드 작성하기

index() 테스트하기

  • 테스트 통과
@SpringBootTest
class ArticleServiceTest {
    @Autowired
    ArticleService articleService;

    @Test
    void index() {
            // 1. 에상 데이터
            Article a = new Article(1L, "1234", "1234");
            Article b = new Article(2L, "abcd", "1414");
            Article c = new Article(3L, "가나다라", "4321");

            List<Article> expected = new ArrayList<Article>(Arrays.asList(a, b, d));

            // 2. 실제 데이터
            List<Article> articles = articleService.index();

            // 3. 비교 및 검증
            assertEquals(expected.toString(), articles.toString());
    }
}

  • 테스트 실패
    • Article c = new Article(4L, "가나다라", "4321"); 로 일부러 다른 값을 넣어서 테스트를 하면 실패한다.

show() 테스트하기

  • 존재하는 id 조회
@Test 
public void show_성공_존재하는_id() { 
    Long id = 1L; 
    Article expected = new Article(id, "1234", "1234"); 
    Article article = articleService.show(id); 
    asssertEquals(expected.toString(), article.toString()); 
}
  • 존재하지 않는 id 조회
@Test 
public void show_성공_존재하지않는_id() { 
    Long id = -1L; 
    Article expected = null; 
    Article article = articleService.findById(id); 
    asssertEquals(expected, article); 
}

create() 테스트하기

  • 성공
@Test 
public void create_성공_title과_content만_있는_dto_입력() { 
    Stirng title = "가나다라"; 
    String content = "1234"; 
    ArticleForm dto = new ArticleForm(null, title, content); 
    Article expected = new Article(4L, title, content); 
    Article article = articleService.create(dto); 
    assertEquals(expected.toString(), article.toString()); 
}
  • 실패
@Test 
public void create_실패_id가_포함된_dto_입력() { 
    Long id = 4L; 
    String title = "가나다라"; 
    String content = "1234"; 
    ArticleForm dto = new ArticleForm(id, title, content); 
    Article expected = null; 
    Article article = articleService.create(dto); 
    assertEquals(expected, article); 
}