김영한 강사님의 "스프링부트와 JPA 활용1"을 듣다 보면 Section 5에서 "상품 기능 테스트"를 생략하신 것을 볼 수 있다. 이 테스트가 이전에 강의에서 다룬 테스트와 유사하여 생략하였다고 하셨는데 복습겸 궁금하여 테스트 코드를 직접 작성하여 보였다.
MemberServiceTest.java를 참고하여 작성하였고 //given, //when, //then 으로 나누어 작성하니 도움이 많이 되었다.
테스트한 기능은 상품 등록, 상품 목록 조회, 상품 조회이다.
파일 위치는 jpashop/src/test/java/jpabook/jpashop/service/ItemServiceTest.java 으로 지정하였다.
package jpabook.jpashop.service;
import jpabook.jpashop.domain.Member;
import jpabook.jpashop.domain.item.Item;
import jpabook.jpashop.repository.ItemRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
//JUnit4
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional //롤백을 위해
public class ItemServiceTest {
@Autowired
ItemService ItemService;
@Autowired
ItemRepository ItemRepository;
@Test
public void 상품_등록() throws Exception{
//given
Item item = new Item();
//when
ItemService.saveItem(item);
//then
assertEquals(item, ItemRepository.findOne(item.getId()));
}
@Test
public void 상품_목록_조회() throws Exception{
//given
List<Item> itemList = new ArrayList<>();
//when
List<Item> result = ItemService.findItems();
//then
assertEquals(itemList, result);
}
@Test
public void 상품_조회() throws Exception{
//given
Item item = new Item();
ItemService.saveItem(item);
//when
Item result = ItemService.findOne(item.getId());
//then
assertEquals(item,result);
}
}
'Spring > SpringBoot&JPA' 카테고리의 다른 글
[스프링부트와 JPA 활용 1] Section7. 웹 계층 개발 (0) | 2023.11.14 |
---|---|
[스프링부트와 JPA 활용 1] Section6. 주문 도메인 개발 (0) | 2023.11.08 |
[스프링부트와 JPA 활용 1] Section5. 상품 도메인 개발 (1) | 2023.11.01 |
[스프링부트와 JPA 활용 1] Section4. 회원 도메인 개발 (1) | 2023.11.01 |
[스프링부트와 JPA 활용 1] Section3. 애플리케이션 구현 준비 (0) | 2023.11.01 |