Skip to content

Commit

Permalink
Test : Career 활동 삭제 테스트 코드 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
hyeonda02 committed Jul 22, 2024
1 parent 5b6b395 commit 00f3093
Show file tree
Hide file tree
Showing 8 changed files with 187 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -33,15 +32,34 @@ public CareerResponse<CareerResponseDto.CareerResultDto> create(@RequestBody @Va
CareerConverter.tocareerResultDto(career));
}


@DeleteMapping("/{careerId}")
@Operation(summary = "활동 삭제 API", description = "내 커리어 - 활동을 삭제하는 API")
@Parameters({
@Parameter(name="careerId",description = "활동 아이디, path variable 입니다.")
})
@Parameter(name="careerId", description = "활동 Id, path variable 입니다.",example = "1")
public CareerResponse<Object> delete(@PathVariable Long careerId){
LoginUser loginUser = LoginUser.get();
careerService.deleteCareer(careerId);
return CareerResponse.success(CareerStatusCode.OK,
CareerResponseMessage.CAREER_DELETE_SUCCESS,null);
}

@PatchMapping("/{careerId}")
@Operation(summary = "활동 수정 API", description = "내 커리어 - 활동을 수정하는 API")
@Parameter(name="careerId", description = "활동 Id, path variable 입니다.",example = "1")
public CareerResponse<Object> update(@RequestBody @Valid CareerRequestDto.UpdateCareerDto request,
@PathVariable Long careerId) {
LoginUser loginUser = LoginUser.get();
Career updateCareer = careerService.updateCareer(careerId, request);
return null;
}
}










Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ public class CareerResponseMessage {
public static final String CAREER_PERIOD_FAIL = "시작 날짜는 종료 날짜보다 앞에 있어야 합니다.";
public static final String CATEGORY_NOT_FOUND = "존재하는 카테고리 Id가 아닙니다.";
public static final String CAREER_DELETE_SUCCESS = "활동 삭제가 정상적으로 이루어졌습니다.";
public static final String CAREER_DELETE_FAIL = "활동 삭제를 실패했습니다.";









}
24 changes: 24 additions & 0 deletions src/main/java/umc/kkijuk/server/career/dto/CareerRequestDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,28 @@ public static class CareerDto{
int category;
}

@Getter
@Builder
public static class UpdateCareerDto{
@Size(max = 20)
@Schema(description = "활동명", example = "IT 서비스 개발 동아리", type="string")
String careerName;
@Size(max = 20)
@Schema(description = "활동 별칭", example = "동아리", type="string")
String alias;
@Size(max = 50)
@Schema(description = "활동 내역", example = "활동 내역 최대 50자까지 입력 가능(선택사항입니다.)",type = "string")
String summary;
@Schema(description = "활동 여부", example = "false", type = "boolean")
Boolean isCurrent;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Asia/Seoul")
@Schema(description = "활동 시작 날짜", example = "2024-04-14", type="string")
LocalDate startDate;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Asia/Seoul")
@Schema(description = "활동 종료 날짜", example = "2024-07-20", type = "string")
LocalDate endDate;
@Schema(description = "활동 카테고리", example = "1", type = "int")
int category;
}

}
16 changes: 16 additions & 0 deletions src/main/java/umc/kkijuk/server/career/dto/CareerResponseDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDate;

public class CareerResponseDto {

@Getter
Expand All @@ -17,5 +19,19 @@ public static class CareerResultDto{
private Long careerId;
}

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class UpdateCareerResultDto{
String careerName;
String alias;
String summary;
Boolean isCurrent;
LocalDate startDate;
LocalDate endDate;
int category;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ public interface CareerService {
Career createCareer(CareerRequestDto.CareerDto request);
void deleteCareer(Long careerId);
Optional<Career> findCareer(Long value);
Career updateCareer(Long careerId, CareerRequestDto.UpdateCareerDto request);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package umc.kkijuk.server.career.service;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import umc.kkijuk.server.career.controller.exception.CareerNotFoundException;
Expand All @@ -11,8 +14,11 @@
import umc.kkijuk.server.career.repository.CareerRepository;
import umc.kkijuk.server.career.repository.CategoryRepository;

import java.beans.PropertyDescriptor;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

@Service
@RequiredArgsConstructor
Expand All @@ -32,16 +38,23 @@ public Career createCareer(CareerRequestDto.CareerDto request) {
@Override
@Transactional
public void deleteCareer(Long careerId) {
Optional<Career> career = careerRepository.findById(careerId);
if (career.isEmpty()) {
throw new CareerNotFoundException(CareerResponseMessage.CAREER_NOT_FOUND.toString());
}
Optional<Career> career = findCareer(careerId);
careerRepository.delete(career.get());
}
@Override
public Career updateCareer(Long careerId, CareerRequestDto.UpdateCareerDto request) {
Career career = findCareer(careerId).get();
if(request.getCategory()!=0){
career.setCategory(categoryRepository.findById(Long.valueOf(request.getCategory())).get());
}
return careerRepository.save(career);
}


@Override
public Optional<Career> findCareer(Long value) {
return careerRepository.findById(value);
public Optional<Career> findCareer(Long careerId) {
return Optional.ofNullable(careerRepository.findById(careerId).orElseThrow(
() -> new CareerNotFoundException(CareerResponseMessage.CAREER_NOT_FOUND.toString())));
}

private int parsingYear(CareerRequestDto.CareerDto request){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,22 @@
import org.springframework.test.web.servlet.MockMvc;
import umc.kkijuk.server.career.controller.CareerController;
import umc.kkijuk.server.career.controller.exception.CareerExceptionControllerAdvice;
import umc.kkijuk.server.career.controller.exception.CareerNotFoundException;
import umc.kkijuk.server.career.controller.response.CareerResponse;
import umc.kkijuk.server.career.controller.response.CareerResponseMessage;
import umc.kkijuk.server.career.domain.Career;
import umc.kkijuk.server.career.domain.Category;
import umc.kkijuk.server.career.dto.CareerRequestDto;
import umc.kkijuk.server.career.repository.CareerRepository;
import umc.kkijuk.server.career.repository.CategoryRepository;

import java.time.LocalDate;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

Expand All @@ -37,7 +40,10 @@ public class CareerServiceTest {
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private CareerRepository careerRepository;
@Autowired
private CareerExceptionControllerAdvice careerExceptionControllerAdvice;
private Career career;


@BeforeEach
Expand All @@ -59,10 +65,20 @@ void init() {
categoryRepository.save(category2);
categoryRepository.save(category3);
categoryRepository.save(category4);

career = Career.builder().id(1L).name("tet1")
.alias("alias2")
.summary("summary")
.current(false)
.startdate(LocalDate.of(2024, 4, 10))
.enddate(LocalDate.of(2024, 7, 20))
.category(category1)
.build();
careerRepository.save(career);
}

@Test
void 새로운_career_만들기() {
void create_새로운_career_만들기() {
//given
CareerRequestDto.CareerDto careerCreateDto = CareerRequestDto.CareerDto.builder()
.careerName("test")
Expand All @@ -76,7 +92,7 @@ void init() {
Career career = careerService.createCareer(careerCreateDto);
//then
assertAll(
() -> assertThat(career.getId()).isEqualTo(1L),
() -> assertThat(career.getId()).isEqualTo(2L),
() -> assertThat(career.getName()).isEqualTo("test"),
() -> assertThat(career.getAlias()).isEqualTo("alias"),
() -> assertThat(career.getCurrent()).isEqualTo(false),
Expand All @@ -88,6 +104,23 @@ void init() {
);
}
@Test
void delete_기존_career_삭제(){
//given
careerService.deleteCareer(career.getId());
//when
//then
Optional<Career> deletedCareer = careerRepository.findById(career.getId());
assertThat(deletedCareer).isEmpty();

}
@Test
void delete_삭제시_없는_careerId_요청은_에러() {
//given
//when
//then
assertThrows(CareerNotFoundException.class, () -> careerService.deleteCareer(999L));
}
@Test
void CareerExceptionControllerAdvice가_올바른_예외_응답을_반환하는지_검증() {
//given
InvalidFormatException invalidFormatException = mock(InvalidFormatException.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package umc.kkijuk.server.career.service;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import umc.kkijuk.server.career.controller.exception.CareerNotFoundException;
import umc.kkijuk.server.career.domain.Career;
import umc.kkijuk.server.career.repository.CareerRepository;

import javax.swing.text.html.Option;
import java.time.LocalDate;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class CareerServiceUnitTest {
@Mock
private CareerRepository careerRepository;
@InjectMocks
private CareerServiceImpl careerService;
private Career career;
@BeforeEach
void init() {
career = Career.builder()
.id(1L)
.name("test")
.alias("alias")
.summary("summary")
.current(false)
.startdate(LocalDate.of(2024, 4, 10))
.enddate(LocalDate.of(2024, 7, 20))
.build();
}

@Test
void delete_기존_career_삭제() {
//given
when(careerRepository.findById(anyLong())).thenReturn(Optional.of(career));
//when
careerService.deleteCareer(1L);
//then
verify(careerRepository,times(1)).delete(career);
}

@Test
void delete_삭제시_없는_careerId_요청은_에러() {
//given
when(careerRepository.findById(anyLong())).thenReturn(Optional.empty());
//when
//then
assertThrows(CareerNotFoundException.class, ()->{
careerService.deleteCareer(1L);});
verify(careerRepository,never()).delete(any(Career.class));
}
}

0 comments on commit 00f3093

Please sign in to comment.