@Test
public void 물건_구매_실패_테스트() {
Store store = this.storeService.saveStore("store", StoreType.KOREAN);
Item item = this.itemService.itemSave(store.getStoreId(), "비빔밥", 8000, 1);
Customer c1 = this.customerService.customerSave("c1", 5000);
Customer c2 = this.customerService.customerSave("c2", 10000);
Customer c3 = this.customerService.customerSave("c3", 10000);
{
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class,
() -> this.customerService.buyItem(c1.getCustomerId(), item.getItemId())
);
assertThat(illegalStateException.getMessage()).isEqualTo("소지금보다 비싼 물건을 구매할 수 없습니다.");
}
{
CustomerItem customerItem = this.customerService.buyItem(c2.getCustomerId(), item.getItemId());
assertThat(customerItem.getCustomerId()).isEqualTo(c2.getCustomerId());
assertThat(customerItem.getItemId()).isEqualTo(item.getItemId());
}
{
IllegalStateException illegalStateException2 = assertThrows(IllegalStateException.class,
() -> this.customerService.buyItem(c3.getCustomerId(), item.getItemId())
);
assertThat(illegalStateException2.getMessage()).isEqualTo("남은 재고가 없습니다.");
}
}
@Transactional(rollbackFor = IllegalStateException.class)
public CustomerItem buyItem(long customerId, long itemId) {
Item item = this.itemService.minusRemained(itemId);
Customer customer = this.minusPoint(customerId, item);
CustomerItem customerItem = this.customerItemService.customerItemSave(customer.getCustomerId(), item.getItemId());
return customerItem;
}
public Item minusRemained(long itemId) {
Item item = this.itemRepository.findById(itemId)
.orElseThrow(() -> new IllegalStateException("해당하는 물품이 없습니다."));
if (item.getRemained() == 0) {
throw new IllegalStateException("남은 재고가 없습니다.");
}
item.setRemained(item.getRemained() - 1);
return item;
}
this is my code.
And at test, I can pass first test case.
But the remain does not rollback.
so after first test, item's remained became 0.
I want to buyItem method to rollback if IllegalStateException has come. Thank you.
I tried using new entity. And it worked well. But I am using spring data JPA. So I want to utilize EntityManager.