개념
- 특정 객체가 정상적으로 생성되는지 확인하는 테스트
- 주의!: 서비스 테스트는 실제 DB에 영향을 주지 않으므로, 리파지토리의 함수의 호출 자체만을 확인해야한다.
성공 테스트
given
- 생성에 필요한 더미 정보들을 준비한다. ( 메서드의 파라미터 정보들 )
- 예시) 상품 등록에 메서드가 상품 등록 정보(dto), 멤버 정보가 필요한 경우
- productService.createProduct(dto, memberDetails);
@Test
void 상품_등록_성공() {
// given
//멤버 정보
int mileage = 1000;
Status status = Status.ACTIVE;
String socialId = "1111";
Role role = Role.USER;
Member member = Member.of(mileage, status, socialId, role);
CustomMemberDetails memberDetails = new CustomMemberDetails(member);
//상품 정보
String name = "상품1";
Integer initialPrice = 10000;
String content = "이것은 상품 설명 부분";
String category = Category.BOOK.getKey();
LocalDateTime deadline = LocalDateTime.now().plusDays(3);
ProductCreateRequest request = new ProductCreateRequest(
name,
initialPrice,
content,
category,
deadline
);
}
이미지 파일 첨부 경우
- 생성 테스트를 진행할 때, 이미지 파일까지 같이 전달을 해야하는 상황이 발생한다.
- MockMultipartFile 클래스를 활용
MockMultipartFile image1 = new MockMultipartFile(
"image1",
"product_image1.png",
IMAGE_PNG_VALUE,
"imageDummy".getBytes()
);
MockMultipartFile image2 = new MockMultipartFile(
"image2",
"product_image2.png",
IMAGE_PNG_VALUE,
"imageDummy".getBytes()
);
List<MultipartFile> images = Arrays.asList(image1, image2);
when
- 해당 메서드 내에서 호출되는 외부 객체(Mock)의 메서드의 행동을 지정한다.
- 그 후, 해당 메서드를 호출
// when
// 행동 지정
when(productRepository.save(any(Product.class))).thenReturn(null);
// 서비스 메서드 호출
productService.createProduct(request, memberDetails);
Then
- 보통 생성 메서드는 반환값이 없으므로, 호출 검증으로 진행
// then
//productRepository의 save 메서드가 1번 호출 되었는가?
verify(productRepository, times(1)).save(any(Product.class));
실패 테스트
생성 테스트를 진행할 때는, 생성할 때 필요한 정보들에 대한 예외가 제대로 잡아지는지를 확인해야 한다.
Given
- 테스트 하고 싶은 정보에 잘못된 정보를 입력한다.
@Test
void 실패_유효하지_않은_가격() {
// given
//멤버 정보
int mileage = 1000;
Status status = Status.ACTIVE;
String socialId = "1111";
Role role = Role.USER;
Member member = Member.of(mileage, status, socialId, role);
CustomMemberDetails memberDetails = new CustomMemberDetails(member);
//상품 정보
String name = "상품1";
Integer initialPrice = -1; //유효하지 않은 가격
String content = "이것은 상품 설명 부분";
String category = Category.BOOK.getKey();
LocalDateTime deadline = LocalDateTime.now().plusDays(3);
ProductCreateRequest request = new ProductCreateRequest(
name,
initialPrice,
content,
category,
deadline
);
}
검증
- 유효하지 않은 값이 들어왔을 때, 적절한 예외를 잘 발생시키는지 확인한다.
커스텀 BusinessException인 경우
- 에러 코드가 동일한지 까지 확인한다.
// when
BusinessException exception = assertThrows(BusinessException.class, () -> productService.createProduct(request, images, memberDetails));
// then
assertThat(exception.getErrorCode()).isEqualTo(ProductErrorCode.INVALID_CATEGORY);
내장 예외인 경우
- 해당 예외를 발생시키는지만 확인한다.
assertThrows(IllegalArgumentException.class, () -> productService.readProduct(productId2));
'Spring > 테스트' 카테고리의 다른 글
Service - 수정 테스트 (0) | 2024.03.12 |
---|---|
Service - 삭제 테스트 (0) | 2024.03.12 |
Service - 조회 테스트 (0) | 2024.03.12 |
Service 테스트 (0) | 2024.03.11 |
Postman 파일 첨부 요청 방법 (0) | 2024.02.07 |