Entity Convention
@Entity
@Comment("상품 카테고리 정보")
@Getter
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@SQLRestriction("use_flag = 'Y'")
public class ProductCategory extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Comment("상품 카테고리 정보 IDX")
private Long productCategoryId;
@Column(nullable = false, length = 100)
@Comment("카테고리명")
private String name;
@Builder
public ProductCategory(String name) {
this.name = name;
}
public static ProductCategory addOf(ProductCategoryAddReqDto dto) {
return ProductCategory.builder()
.name(dto.name())
.build();
}
public void modify(final String name) {
this.name = name;
}
}
- 기본 생성자의 접근 권한은 Protected로 설정
- 불필요한 필드는 생성자, Builder 등을 제공 X
- Setter 사용 지양
테스트 코드 작성 시 ID가 필요한 경우
@Test
@DisplayName("실패 - 중복된 카테고리명")
void 실패_중복된_카테고리명() {
// given
ProductCategoryModifyReqDto dto = createProductCategoryModifyReqDto();
ProductCategory productCategory = Mockito.spy(createProductCategory());
given(productCategory.getProductCategoryId()).willReturn(2L);
given(productCategoryRepository.findById(any())).willReturn(Optional.of(productCategory));
given(productCategoryRepository.findByName(categoryName)).willReturn(Optional.of(productCategory));
// when
assertThatThrownBy(() -> productCategoryService.modifyProductCategory(dto))
.isInstanceOf(CustomException.class)
.hasFieldOrPropertyWithValue("errorCode", ErrorCode.DUPLICATED_CATEGORY_NAME);
// then
then(productCategoryRepository).should().findById(any());
then(productCategoryRepository).should().findByName(categoryName);
}
Mockito의 spy 메소드는 기존 객체를 그대로 가지고 있으면서 특정 메소드만 스터빙할 수 있습니다. 이렇게 spy를 사용하면 프로덕션 코드에 불필요한 코드가 추가로 필요하지 않고, ID 혹은 원하는 필드는 세팅할 수 있습니다.
'Programming > SpringBoot' 카테고리의 다른 글
[SpringBoot] JPA 동적 스키마 (1) | 2024.11.06 |
---|---|
[SpringBoot] @ModelAttribute 작동 원리 (0) | 2024.07.17 |
[SpringBoot] @ResponseBody 원리 (0) | 2024.01.29 |
[SpringBoot] Model VS ModelMap (0) | 2023.12.26 |
[SpringBoot] JSP에서의 예외 처리 (0) | 2023.12.19 |