

package com.example.tdd_study.product;
import org.springframework.util.Assert;
import lombok.Getter;
@Getter
public class Product {
private Long id;
private final String name;
private final int price;
public Product(String name, int price) {
Assert.hasText(name, "상품명은 필수입니다.");
Assert.isTrue(price > 0, "상품 가격은 0보다 커야 합니다.");
this.name = name;
this.price = price;
}
public void assignId(Long id) {
this.id = id;
}
}com.example.tdd_study.product임을 주의해 주세요.package com.example.tdd_study.product;
import java.util.HashMap;
import java.util.Map;
public class ProductRepository {
private Map<Long, Product> persistence = new HashMap<>();
private Long sequence = 0L;
public void save(Product product) {
product.assignId(++sequence);
persistence.put(product.getId(), product);
}
}package com.example.tdd_study.product;
public class ProductService {
// Repository를 의존하게 변경
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public void register(String name, int price) {
Product product = new Product(name, price);
productRepository.save(product);
}
}package com.example.tdd_study.product;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ProductServiceTest {
private ProductService productService;
private ProductRepository productRepository;
@BeforeEach
void setUp() {
// Service가 Repository를 필요로 하므로 주입해줍니다.
productRepository = new ProductRepository();
productService = new ProductService(productRepository);
}
@Test
void 상품_등록_성공() {
// given
String name = "아메리카노";
int price = 4500;
// when
productService.register(name, price);
// then: Repository를 통해서 검증하는 것도 좋은 방법입니다.
// 하지만 지금은 에러 없이 실행되는지 확인하는 것에 집중합니다.
}
}다음 시간에는 이제 단순한 자바 클래스가 아닌, 실제 스프링 빈(Spring Bean)을 활용하여 도메인 중심의 설계를 적용해 보겠습니다.