Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅ Refactor: FoodServiceTest Mock으로 리팩토링 (#29) #32

Merged
merged 15 commits into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,8 @@ public static Food createFoodFromFavoriteFood(FavoriteFood favoriteFood) {
favoriteFood.addCount();
return Food.createFood(favoriteFood.getName(), favoriteFood.getUser(), favoriteFood.getBaseNutrition());
}

public void setId(Long id) {
this.id = id;
}
}
3 changes: 2 additions & 1 deletion src/main/java/com/diareat/diareat/food/domain/Food.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.time.LocalDate;
Expand Down Expand Up @@ -56,4 +55,6 @@ public void updateFood(String name, BaseNutrition baseNutrition) {
public boolean isFavorite() {
return this.favoriteFood != null;
}

public void setId(long id) {this.id = id;}
}
26 changes: 25 additions & 1 deletion src/main/java/com/diareat/diareat/food/service/FoodService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
import com.diareat.diareat.user.domain.User;
import com.diareat.diareat.user.repository.UserRepository;
import com.diareat.diareat.util.api.ResponseCode;
import com.diareat.diareat.util.exception.FavoriteException;
import com.diareat.diareat.util.exception.FoodException;
import com.diareat.diareat.util.exception.UserException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.registry.LocateRegistry;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
Expand All @@ -41,6 +41,7 @@ public Long saveFood(CreateFoodDto createFoodDto) {
// 회원이 특정 날짜에 먹은 음식 반환
@Transactional(readOnly = true)
public List<ResponseFoodDto> getFoodListByDate(Long userId, LocalDate date){
validateUser(userId);
List<Food> foodList = foodRepository.findAllByUserIdAndDate(userId, date);
return foodList.stream()
.map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList());
Expand All @@ -57,6 +58,7 @@ public void updateFood(UpdateFoodDto updateFoodDto) {
// 음식 삭제
@Transactional
public void deleteFood(Long foodId) {
validateFood(foodId);
foodRepository.deleteById(foodId);
}

Expand All @@ -73,6 +75,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) {
//즐겨찾기 음식 리스트 반환
@Transactional(readOnly = true)
public List<ResponseFavoriteFoodDto> getFavoriteFoodList(Long userId){
validateUser(userId);
List<FavoriteFood> foodList = favoriteFoodRepository.findAllByUserId(userId);
return foodList.stream()
.map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(), favoriteFood.getName(),
Expand All @@ -89,19 +92,22 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) {
// 즐겨찾기 해제
@Transactional
public void deleteFavoriteFood(Long favoriteFoodId) {
validateFavoriteFood(favoriteFoodId);
favoriteFoodRepository.deleteById(favoriteFoodId);
}

@Transactional(readOnly = true)
// 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요)
public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) {
validateUser(userId);
List<Food> foodList = foodRepository.findAllByUserIdAndDate(userId, date);
return calculateNutritionSumAndRatio(userId, foodList, date, 1);
}

@Transactional(readOnly = true)
// 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요)
public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) {
validateUser(userId);
LocalDate endDate = LocalDate.now();
List<Food> foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate);

Expand All @@ -111,6 +117,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) {
@Transactional(readOnly = true)
// 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요)
public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) {
validateUser(userId);
LocalDate endDate = LocalDate.now();
List<Food> foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate);

Expand All @@ -120,6 +127,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) {
@Transactional(readOnly = true)
// 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요)
public ResponseFoodRankDto getBestFoodByWeek(Long userId) {
validateUser(userId);
LocalDate endDate = LocalDate.now();
List<Food> foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate);

Expand All @@ -140,6 +148,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) {
@Transactional(readOnly = true)
// 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요)
public ResponseFoodRankDto getWorstFoodByWeek(Long userId) {
validateUser(userId);
LocalDate endDate = LocalDate.now();
List<Food> foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate);

Expand Down Expand Up @@ -198,6 +207,21 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId,
return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat);
}

private void validateUser(Long userId) {
if (!userRepository.existsById(userId))
throw new UserException(ResponseCode.USER_NOT_FOUND);
}

private void validateFood(Long foodId) {
if (!foodRepository.existsById(foodId))
throw new FoodException(ResponseCode.FOOD_NOT_FOUND);
}

private void validateFavoriteFood(Long favoriteFoodId) {
if (!favoriteFoodRepository.existsById(favoriteFoodId))
throw new FavoriteException(ResponseCode.FAVORITE_NOT_FOUND);
}
Comment on lines +210 to +223
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

보통 이렇게 두 가지 이상의 Service에서 같은 검증 로직을 공유하는 경우에는 util 패키지에 별도의 싱글톤 클래스를 선언하여 그 내부 메서드를 사용하는 방식을 채택하는 경우도 있습니다만, Service에 두개뿐이라 그렇게까지 할 필요는 없는 것 같습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조언 감사합니다!



/**
* 메서드 구현 유의사항
Expand Down
Loading