Spring Boot 테스트 클래스 참조

김효중·2025년 7월 28일

QuestionRepository 생성하기

public interface QuestionRepository extends JpaRepository<Question, Integer> {
   // JPA가 제공하는 인터페이스를 상속받음
}

JUnit을 사용하려면 build.gradle에 추가

dependencies {
(... 생략 ...)
    testImplementation 'org.junit.jupiter:junit-jupiter' 
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

SbbApplicationTests 클래스

@SpringBootTest
class SbbApplicationTests {

    @Autowired //(객체를 자동으로 만듬)
    private QuestionRepository questionRepository;

    @Test
    void testJpa() {        
       //구현
    }
}

리포지터리의 메서드 예시


표 출처 : https://wikidocs.net/160890#_3

Lazy Loading vs Eager Loading

ex) Answer 클래스의 ManyToOne관계 (N개의 답변 → 1개의 질문)
해당 구도에서 연결된 데이터를 조회할 때에 발생함.

기본적으로 findAll을 하면 우선적으로는 Answer를 조회 하겠지만
연결된 Question 데이터에 접근이 필요해지는 시점에 지연로딩으로 한번 더 조회가 실행

관계된 데이터를 필요할 때 가져오는 방식 >> 지연(Lazy) 방식
관계된 데이터를 즉시 가져오는 방식 >> 즉시(Eager) 방식

테스트환경에선 @Transactional을 사용하여 Lazy 오류를 막을 것 or
@OneToMany, @ManyToOne 애너테이션의 옵션
fetch=FetchType.LAZY or fetch=FetchType.EAGER 설정할 수 있음

profile
안녕하세요

0개의 댓글