게시글
질문&답변
2021.02.18
@PersistenceContext 제외했는데 EntityManager 가 테스트할 때 null 입니다.
감사합니다. 정상적으로 동작 확인하였습니다.
- 0
- 4
- 1.3K
질문&답변
2021.02.08
@PersistenceContext 제외했는데 EntityManager 가 테스트할 때 null 입니다.
안녕하세요. OrderServiceTest.상품주문() 를 실행할 경우 1. Book에 대해서 RequiredArgsConstructor를 주석처리하고, PersistenceContext를 사용할 경우 정상적으로 동작 2. RequiredArgsConstructor를 사용하고 PersistenceContext를 주석처리해서 테스트를 실행할 경우 오류가 발생합니다. debug 결과 EntityManager가 null 이었습니다. (사진)================== ItemRepository.java package jpabook.jpashop.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import jpabook.jpashop.domain.item.Item; @Repository //@RequiredArgsConstructor public class ItemRepository { @PersistenceContext private EntityManager em; public void save (Item item) { if (item.getId() == null) { em.persist(item); } else { em.merge(item); } } public Item findOne (Long id) { return em.find(Item.class, id); } public List findAll () { return em.createQuery("select i from Item i", Item.class) .getResultList(); } } ============= OrderServiceTest.java package jpabook.jpashop.service; import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import javax.persistence.EntityManager; import org.junit.jupiter.api.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 jpabook.jpashop.domain.Address; import jpabook.jpashop.domain.Member; import jpabook.jpashop.domain.Order; import jpabook.jpashop.domain.OrderStatus; import jpabook.jpashop.domain.item.Book; import jpabook.jpashop.exception.NotEnoughStockException; import jpabook.jpashop.repository.OrderRepository; @RunWith (SpringRunner.class) @SpringBootTest @Transactional class OrderServiceTest { @Autowired EntityManager em; @Autowired OrderService orderService; @Autowired OrderRepository orderRepository; @Test public void 상품주문() throws NotEnoughStockException { //given Member member = new Member(); member.setName("kim"); member.setAddress(new Address("서울", "경기", "111-111")); em.persist(member); Book book = new Book(); book.setName("테스트 JPA"); book.setPrice(10000); book.setStockQuantity(10); em.persist(book); //when int orderCount = 2; Long orderId = orderService.order(member.getId(), book.getId(), orderCount); //then Order getOrder = this.orderRepository.findOne(orderId); assertEquals("상품 주문시 상태는 ORDER", OrderStatus.ORDER, getOrder.getStatus()); assertEquals("주문한 상품 종류 수가 정확해야 한다.", 1, getOrder.getOrderItems().size()); assertEquals("주문 가격은 가격 * 수량이다.", 10000 * 2, getOrder.getTotalPrice()); assertEquals("주문 수량만큼 재고가 줄어야 한다.",8, book.getStockQuantity()); } @Test public void 상품수량_재고수량초과() { //given Member member = new Member(); member.setName("kim"); member.setAddress(new Address("서울", "경기", "111-111")); em.persist(member); Book book = new Book(); book.setName("테스트 JPA"); book.setPrice(10000); book.setStockQuantity(10); em.persist(book); //when int orderCount = 11; NotEnoughStockException thrown = assertThrows(NotEnoughStockException.class, () -> orderService.order(member.getId(), book.getId(), orderCount)); assertEquals("no more stock", thrown.getMessage()); } @Test public void 주문취소() throws NotEnoughStockException { //given Member member = new Member(); member.setName("kim"); member.setAddress(new Address("서울", "경기", "111-111")); em.persist(member); Book book = new Book(); book.setName("테스트 JPA"); book.setPrice(10000); book.setStockQuantity(10); em.persist(book); int orderCount = 2; Long orderId = orderService.order(member.getId(), book.getId(), orderCount); //when orderService.cancelOrder(orderId); //then Order getOrder = orderRepository.findOne(orderId); assertEquals("주문 취소시 상태는 CANCEL 이다.", OrderStatus.CANCEL, getOrder.getStatus()); assertEquals("주문이 취소된 상품은 그만큼 재고가 증가해야 한다.", 10, book.getStockQuantity()); } @Test public void 상품주문_재고수량초과() { fail("Not yet implemented"); } } ============= build.gradle plugins { id 'org.springframework.boot' version '2.4.2' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' id 'war' } group = 'jpabook' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { //mavenCentral() maven { url = "http://acha.ubivelox.com:8991/nexus/content/groups/public/" } } dependencies { implementation 'org.springframework.boot:spring-boot-starter-amqp' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.6.3' // for devtools developmentOnly 'org.springframework.boot:spring-boot-devtools' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' testImplementation 'org.springframework.amqp:spring-rabbit-test' //JUnit4 추가 testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation("org.junit.vintage:junit-vintage-engine") { exclude group: "org.hamcrest", module: "hamcrest-core" } } test { useJUnitPlatform() }
- 0
- 4
- 1.3K