java static사용시 주의할점

wellbeing-dough·2024년 1월 5일
1

문제상황


하나의 테스트 코드가 안돌아간다


하나만 따로 돌리면 돌아간다.... ㄷㄷ

@RepositoryTest
@Slf4j
class JobInspectionRepositoryImplTest {

    @Autowired
    private JobInspectionRepository jobInspectionRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Test
    void 직업_분류_상태를_식별자로_직업_분류를_전체_조회한다() {
        // given
        int 무형문화재직업검토_인덱스 = 0;
        int 준위직업검토_인덱스 = 1;

        UserProfileEntity 동우 = 김동우;
        UserProfileEntity 명철 = 최명철;

        userProfileRepository.save(동우);
        userProfileRepository.save(명철);

        JobInspectEntity 무형문화재직업검토 = 무형문화재_직업_검토(동우.getId());
        JobInspectEntity 준위직업검토 = 준위_직업_검토(명철.getId());

        jobInspectionRepository.save(무형문화재직업검토);
        jobInspectionRepository.save(준위직업검토);

        InspectionUserProfileData 동우_프로필 = new InspectionUserProfileData(동우.getId(), 동우.getName());
        InspectionUserProfileData 명철_프로필 = new InspectionUserProfileData(명철.getId(), 명철.getName());

        // when
        List<GetJobInspectionResponse> byStatus = jobInspectionRepository.findAllJobInspectByStatus();

        // then
        assertAll(
                () -> assertThat(byStatus.get(무형문화재직업검토_인덱스))
                        .extracting("jobGroupName",
                                "jobDetailName",
                                "status",
                                "userGender",
                                "userProfileData"
                        )
                        .containsExactly(무형문화재직업검토.getJobGroupName(),
                                무형문화재직업검토.getJobDetailName(),
                                무형문화재직업검토.getStatus(),
                                무형문화재직업검토.getUserGender(),
                                동우_프로필
                        ),

                () -> assertThat(byStatus.get(준위직업검토_인덱스))
                        .extracting("jobGroupName",
                        "jobDetailName",
                        "status",
                        "userGender",
                        "userProfileData"
                        )
                        .containsExactly(준위직업검토.getJobGroupName(),
                                준위직업검토.getJobDetailName(),
                                준위직업검토.getStatus(),
                                준위직업검토.getUserGender(),
                                명철_프로필
                        )
        );

    }
}
@RepositoryTest
@Slf4j
public class UnivInspectionRepositoryImplTest {

    @Autowired
    private UnivInspectRepository univInspectRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Test
    void 대학_분류_상태를_식별자로_대학_분류를_전체_조회한다() {
        // given
        int 하얼빈대학교대학검토_인덱스 = 0;
        int 나고야대학교대학검토_인덱스 = 1;

        UserProfileEntity 동우 = 김동우;
        UserProfileEntity 명철 = 최명철;

        userProfileRepository.save(동우);
        userProfileRepository.save(명철);

        UnivInspectEntity 하얼빈대학교대학검토 = 하얼빈대학교_대학_검토(동우.getId());
        UnivInspectEntity 나고야대학교대학검토 = 나고야대학교_대학_검토(명철.getId());

        univInspectRepository.save(하얼빈대학교대학검토);
        univInspectRepository.save(나고야대학교대학검토);

        InspectionUserProfileData 동우_프로필 = new InspectionUserProfileData(동우.getId(), 동우.getName());
        InspectionUserProfileData 명철_프로필 = new InspectionUserProfileData(명철.getId(), 명철.getName());

        // when
        List<GetUnivInspectionResponse> byStatus = univInspectRepository.findAllUnivInspectByStatus();

        System.out.println(byStatus.size());

        // then
        assertAll(
                () -> assertThat(byStatus.get(하얼빈대학교대학검토_인덱스))
                        .extracting("univName",
                                "userGender",
                                "status",
                                "userProfileData"
                        )
                        .containsExactly(하얼빈대학교대학검토.getUnivName(),
                                하얼빈대학교대학검토.getUserGender(),
                                하얼빈대학교대학검토.getStatus(),
                                동우_프로필
                        ),

                () -> assertThat(byStatus.get(나고야대학교대학검토_인덱스))
                        .extracting("univName",
                                "userGender",
                                "status",
                                "userProfileData"
                        )
                        .containsExactly(나고야대학교대학검토.getUnivName(),
                                나고야대학교대학검토.getUserGender(),
                                나고야대학교대학검토.getStatus(),
                                명철_프로필
                        )
        );
    }
}

문제 해결

로그찍어보고 디버깅 때려보니까
JobInspectionRepositoryImplTest 동우.getId는 1 명철.getId는 2로 잘 나오는데
UnivInspectionRepositoryImplTest 동우.getId는 3 명철.GetId 4로 나오는 것이였다...

public class UserProfileFixture {

    public static UserProfileEntity 김동우 = UserProfileEntity.builder()
            .name("김동우")
            .phoneNumber("0106333333")
            .kakaoId("fefcsdfa")
            .jobType(JobType.PROFESSIONAL_JOB)
            .jobDetail("무형 문화재")
            .academicBackground("학사")
            .photoFirst("asd")
            .photoSecond("fsd")
            .photoThird("gbvv")
            .income(1000L)
            .age(25)
            .height(170)
            .address("경기도 군포")
            .religion("무교")
            .partnerAgeRange("무관")
            .partnerUnderAge("무관")
            .partnerUpperAge("무관")
            .partnerCondition("무관")
            .partnerHeight("무관")
            .appealPoint("하이")
            .referencePoint("없음")
            .gender(Gender.FEMALE)
            .build();

이렇게 static으로 선언해서 처음에 JobInspectionRepositoryImplTest에서 jpa가 만들어준 id 1이 적용되서 다른곳에서도 똑같이 되는것이였다...
static은 메모리에 고정적으로 할당되어, 프로그램이 종료될 때 해제되는 변수이다
static 키워드를 통해 생성된 정적멤버들은 Heap영역이 아닌 Static영역에 할당된다. Static 영역에 할당된 메모리는 모든 객체가 공유하여 하나의 멤버를 어디서든지 참조할 수 있는 장점을 가지지만 GC가 관리하지 않기 때문에 Static영역에 있는 멤버들은 프로그램의 종료시까지 메모리가 할당된 채로 존재하게 된다

    public static UnivInspectEntity 나고야대학교_대학_검토(Long userProfileId) {
        return UnivInspectEntity.builder()
                .univName("나고야대학교")
                .status(InspectStatus.BEFORE_INSPECT)
                .userGender(Gender.FEMALE)
                .userProfileId(userProfileId)
                .build();
    }

이런식으로 했어야 했다
그리고 테스트 코드에서도

        userProfileRepository.save(동우);
        userProfileRepository.save(명철);

이게 아니라

        UserProfileEntity saved_동우 = userProfileRepository.save(동우);
        UserProfileEntity saved_명철 = userProfileRepository.save(명철);

이렇게 해야 더 깔끔하다

0개의 댓글

관련 채용 정보