Comments (2)
안녕하세요 좋은 글 감사합니다
그런데 트랜잭션 커밋 위치를 바꿔야 되지 않나용..?
protected <T> List<T> saveAll(List<T> entities) {
transaction.begin();
try {
for (var entity : entities) {
entityManager.persist(entity);
setupEntities.add(entity);
}
entityManager.flush();
transaction.commit();
entityManager.clear();
} catch (Exception e) {
transaction.rollback();
throw e;
}
return entities;
}
그리고 테스트용 데이터 삭제안되는거 아래처럼 처리하고 있는데 혹시 문제될 게 있는지 궁금합니다!
private final List<Object> setupEntities = new ArrayList<>();
@AfterEach
protected void deleteSetups() {
transaction.begin();
try {
for (var entity: setupEntities) {
entityManager.remove(entityManager.merge(entity));
entityManager.flush();
}
transaction.commit();
entityManager.clear();
setupEntities.clear();
} catch (Exception e) {
transaction.rollback();
throw e;
}
}
from blog-comment.
그런데 트랜잭션 커밋 위치를 바꿔야 되지 않나용..?
entityManager.persist(entity)
entityManager.flush()
transaction.commit()
entityManager.clear()
트랜잭션 commit시에 flush를 동작시키기 때문에 사실 굳이 flush를 동작 시키지 않아도 되긴 합니다. 그럼에도 flush를 명시적으로 동작시키는건 아무래도 테스트 코드다 보니 앞에 어떤 작업들이 있을지 몰라서 flush를 명시적으로 동작 시켰습니다.
그리고 테스트용 데이터 삭제안되는거 아래처럼 처리하고 있는데 혹시 문제될 게 있는지 궁금합니다!
이렇게 선언하는 것보다 주어진 테스트 코드의 클래스에 @Transactional
추가하고 아래처럼 사용하면 자동으로 rollback이 진행됩니다.
@SpringBootTest(properties = ["spring.profiles.active=test"])
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
class SpringTestSupport {
@Autowired
private lateinit var entityManager: EntityManager
protected fun <T> save(entity: T): T {
entityManager.persist(entity)
flushAndClearPersistentContext()
return entity
}
private fun flushAndClearPersistentContext() {
entityManager.flush()
entityManager.clear()
}
}
@Transactional
internal class BookFindServiceTest(
private val bookRepository: BookRepository,
private val bookFindService: BookFindService
) : SpringTestSupport() {
@Test
internal fun `findById 존재하는 경우`() {
//given
val book = bookRepository.save(
Book(
title = "title",
writer = "writer",
publisher = "publisher",
price = BigDecimal.TEN
)
)
// 위 save 자동 롤백
}
}
이렇게 사용하는 것이 더 효율적이라고 생각합니다.
해당 포스팅은 Spring Batch 테스트 코드에서 @Transactional
을 물고 시작을 할 수 없어 엔티티 메니저를 직접 생성해서 테스트를 진행하는 경우에 해당 하는 자료입니다. Spring Batch 테스트 코드가 아니라면 위 같은 형식으로 하는것을 개인적으로 권장드립니다.
from blog-comment.
Related Issues (20)
- Ktlint 코드 스타일 검사 - Yun Blog | 기술 블로그 HOT 1
- Kotlin으로 Spring 개발할 때 - Yun Blog | 기술 블로그 HOT 3
- 인텔리제이 다국어 message properties - Yun Blog | 기술 블로그 HOT 1
- JPA JPQL의 조회 동작 살펴보기 - Yun Blog | 기술 블로그 HOT 3
- Spring 동일한 Bean(Class)에서 @Transactional 동작 방식 - Yun Blog | 기술 블로그 HOT 1
- Spring Batch Reader 성능 분석 및 측정 part 1 - Yun Blog | 기술 블로그 HOT 2
- Sql을 통해서 테스트 코드를 쉽게 작성하자 - Yun Blog | 기술 블로그 HOT 2
- Exposed - Yun Blog | 기술 블로그 HOT 3
- Checked Exception을 대하는 자세 - Yun Blog | 기술 블로그 HOT 3
- Spring-Jpa Best Practices Step-06 - Setter 사용하지 않기 - Yun Blog | 기술 블로그 HOT 2
- Spring-Jpa Best Practices Step-08 - OneToOne 관계 설정 팁 - Yun Blog | 기술 블로그 HOT 2
- Github Action With Gradle - Yun Blog | 기술 블로그 HOT 1
- Spring Guide - Domain - Yun Blog | 기술 블로그 HOT 1
- Resilience4j를 이용한 서킷 브레이커 기초 - Yun Blog | 기술 블로그 HOT 1
- Spring Batch Test 작성 방법 및 고찰 - Yun Blog | 기술 블로그 HOT 1
- 테스트 대역폭 늘리기 - Yun Blog | 기술 블로그 HOT 4
- 코틀린 groupBy, groupingBy, chunked, flatMap, aggregate 정리 - Yun Blog | 기술 블로그 HOT 1
- Spring Batch 업데이트 성능 최적화 및 분석 - Yun Blog | 기술 블로그 HOT 1
- IntelliJ 자주 사용하는 기능 정리 - Yun Blog | 기술 블로그 HOT 2
- 좋은 코드 설계를 위한 답없는 고민들 - Yun Blog | 기술 블로그 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog-comment.