46.3.12 자동 구성된 Data JPA 테스트들

@DataJpaTest 어노테이션을 사용하여 JPA 응용 프로그램을 테스트 할 수 있습니다. 기본적으로 @Entity 클래스를 검사하고 Spring Data JPA 저장소를 구성합니다. 임베디드 데이터베이스가 클래스 경로에서 사용 가능하면 내장 데이터베이스도 구성됩니다. 일반 @Component 빈은 ApplicationContext로 로드되지 않습니다.

@DataJpaTest가 사용할 수있는 자동 구성 설정 목록은 부록에서 찾을 수 있습니다.

기본적으로 데이터 JPA 테스트는 트랜잭션이며 각 테스트가 끝날 때 롤백됩니다. 자세한 내용은 Spring Framework 참조 문서의 relevant section을 참조하십시오. 원하는 것이 아니라면 다음과 같이 테스트 또는 전체 클래스의 트랜잭션 관리를 비활성화 할 수 있습니다.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringRunner.class)
@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ExampleNonTransactionalTests {

}

데이터 JPA 테스트는 또한 테스트를 위해 특별히 설계된 표준 JPA EntityManager에 대한 대안을 제공하는 TestEntityManager 빈을 주입 할 수 있습니다. @DataJpaTest 인스턴스 외부에서 TestEntityManager를 사용하려는 경우 @AutoConfigureTestEntityManager 어노테이션을 사용할 수도 있습니다. 필요한 경우 JdbcTemplate도 사용할 수 있습니다. 다음 예제는 사용중인 @DataJpaTest 어노테이션을 보여줍니다.

import org.junit.*;
import org.junit.runner.*;
import org.springframework.boot.test.autoconfigure.orm.jpa.*;

import static org.assertj.core.api.Assertions.*;

@RunWith(SpringRunner.class)
@DataJpaTest
public class ExampleRepositoryTests {

	@Autowired
	private TestEntityManager entityManager;

	@Autowired
	private UserRepository repository;

	@Test
	public void testExample() throws Exception {
		this.entityManager.persist(new User("sboot", "1234"));
		User user = this.repository.findByUsername("sboot");
		assertThat(user.getUsername()).isEqualTo("sboot");
		assertThat(user.getVin()).isEqualTo("1234");
	}

}

인 메모리 내장 데이터베이스는 일반적으로 빠르고 설치가 필요 없기 때문에 테스트에 적합합니다. 그러나 실제 데이터베이스에 대해 테스트를 실행하려는 경우 다음 예제와 같이 @AutoConfigureTestDatabase 어노테이션을 사용할 수 있습니다.

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class ExampleRepositoryTests {

	// ...

}

Last updated