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

[BE] Repository를 개선한다. #648

Closed
seokjin8678 opened this issue Jan 9, 2024 · 0 comments
Closed

[BE] Repository를 개선한다. #648

seokjin8678 opened this issue Jan 9, 2024 · 0 comments
Assignees
Labels
BE 백엔드에 관련된 작업 ⚙️ 리팩터링 리팩터링에 관련된 작업 🙋‍♀️ 제안 제안에 관한 작업

Comments

@seokjin8678
Copy link
Collaborator

✨ 세부 내용

1. JpaRepository 인터페이스를 구현하지 않고, Repository 인터페이스를 구현하도록 변경한다.

Repository를 JpaRepository를 구현하는 것이 아닌, Repository를 구현하도록 하여, FakeRepository를 쉽게 만들 수 있도록 하는게 어떨까요?

Service 레이어 테스트 시 Mock을 사용하는 경우가 있는데, Fake를 사용하여 좀 더 신뢰성 있는 테스트가 가능해집니다.

StudentServiceTest를 보시면 다음과 같이 given으로 Stub을 정의하는데, 이는 Fake 객체를 사용한다면 굳이 하지 않아도 될 작업입니다.

@Test
void 존재하지_않는_멤버이면_예외() {
    // given
    given(memberRepository.findById(anyLong()))
        .willReturn(Optional.empty());

    // when & then
    ...
}

@Test
void 존재하지_않는_학교면_예외() {
    // given
    given(schoolRepository.findById(anyLong()))
        .willReturn(Optional.empty());

    // when & then
    ...
}

@Test
void 이미_존재하는_학생이면_예외() {
    // given
    given(studentRepository.existsByMemberId(anyLong()))
        .willReturn(true);

    // when & then
    ...
}

2. default 메서드를 사용하여 findById 메서드를 대체한다.

#594 에서 제시한 이슈입니다.

StudentService의 코드를 보면 다음과 같이 orElseThrow로 핸들링하는 메서드를 볼 수 있습니다.

public class StudentService {
    ...
    private Member findMember(Long memberId) {
        return memberRepository.findById(memberId)
            .orElseThrow(() -> new NotFoundException(ErrorCode.MEMBER_NOT_FOUND));
    }

    private School findSchool(Long schoolId) {
        return schoolRepository.findById(schoolId)
            .orElseThrow(() -> new NotFoundException(ErrorCode.SCHOOL_NOT_FOUND));
    }
    ...
}

해당 메서드는 private으로 만들어 사용중인데, 다른 서비스 클래스를 보더라도 같은 private 메서드를 중복으로 정의하여 사용하는 것을 볼 수 있습니다.

public class MemberService {
    ...
    public MemberProfileResponse findMemberProfile(Long memberId) {
        Member member = memberRepository.findById(memberId)
            .orElseThrow(() -> new NotFoundException(ErrorCode.MEMBER_NOT_FOUND));
        return MemberProfileResponse.from(member);
    }
    ...
}

추후 비즈니스 로직이 추가로 생길 때, 이러한 중복된 코드가 계속 발생할 것 같아 getOrThrow default 메서드를 Repository에 정의하여 중복된 작업을 없애도록 합니다.

⏰ 예상 소요 시간

1시간

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BE 백엔드에 관련된 작업 ⚙️ 리팩터링 리팩터링에 관련된 작업 🙋‍♀️ 제안 제안에 관한 작업
Projects
Status: Done
1 participant