서비스 계층에서 테스트하고 싶은 메서드 -> 오른쪽 마우스 클릭 -> Generate -> Test

생성된 테스트 코드는 src -> test 디렉터리 안에 만들어진다.

@SpringBootTest
class ArticleServiceTest {
@Autowired
ArticleService articleService;
@SpringBootTest : 테스트 코드와 스프링부드를 연동해 통합 테스트를 수행하도록 선언하는 어노테이션@Autowired 어노테이션을 추가해 articleService 객체 주입!! @Test
void index() {
// 1. 예상 데이터
Article a = new Article(1L, "가가가가", "1111");
Article b = new Article(2L, "나나나나", "2222");
Article c = new Article(3L, "다다다다", "3333");
List<Article> expected = new ArrayList<>(Arrays.asList(a,b,c));
// 2. 실제 데이터
List<Article> articles = articleService.index();
// 3. 비교 및 검증
assertEquals(expected.toString(), articles.toString());
}
@Test : 해당 메서드가 테스트 코드임을 선언assertEquals(예상데이터, 실제데이터) 를 사용해서 둘이 일치하는지 확인 

@Test
void show_성공_존재하는_id_입력() {
// 1. 예상 데이터
Long id = 1L;
Article expected = new Article(id, "가가가가", "1111");
// 2. 실제 데이터
Article article = articleService.show(id);
// 3. 비교 및 검증
assertEquals(expected.toString(), article.toString());
}
@Test
void show_실패_존재하지_않는_id_입력() {
// 1. 예상 데이터
Long id = -1L;
Article expected = null;
// 2. 실제 데이터
Article article = articleService.show(id);
// 3. 비교 및 검증
assertEquals(expected, article);
}
@Transactional
@Test
void create_성공_title과_content만_있는_dto_입력() {
// 1. 예상 데이터
String title = "라라라라";
String content = "4444";
ArticleForm dto = new ArticleForm(null, title, content);
Article expected = new Article(4L, "라라라라", "4444");
// 2. 실제 데이터
Article article = articleService.create(dto);
// 3. 비교 및 검증
assertEquals(expected.toString(), article.toString());
}
예상 데이터 : title, content의 데이터를 각각 "라라라라", "4444"로 넣었을 때 예상되는 데이터는 id=4, title="라라라라", content="4444"
실제 데이터 : 서비스의 create 메서드 호출 (매개변수로 dto를 넣음)
즉, title에 "라라라라", content에 "4444"를 넣은 dto를 create로 전달했을 때, 새 Article이 생성되고, id는 DB에 의해 자동으로 부여됨
@Transactional : create, update, delete 테스트할 때는 반드시 테스트를 트랜잭션으로 묶어서 테스트가 종료된 후 롤백될 수 있도록 하는 어노테이션
@Transactional
@Test
void create_실패_id가_포함된_dto_입력() {
// 1. 예상 데이터
Long id = 4L;
String title = "라라라라";
String content = "4444";
ArticleForm dto = new ArticleForm(id, title, content);
Article expected = null;
// 2. 실제 데이터
Article article = articleService.create(dto);
// 3. 비교 및 검증
assertEquals(expected, article);
}
public Article create(ArticleForm dto) {
Article article = dto.toEntity();
if(article.getId() != null) {
return null;
}
return articleRepository.save(article);
}