inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

스프링 통합 테스트

@Transactional rollback이 안되네요

2163

o_o0122

작성한 질문수 1

0

 
 
안녕하세요. 강의 너무 잘 듣고 있습니다.
 
@Transactional을 붙이면 종료하면서 rollback이 되어 테이블에 커밋되지 않는다고 이해했습니다.
로그상에는 rollback이 되었다고 나오는데 쿼리 조회해보면 데이터가 조회가 되네요..
 
로그는 다음과 같습니다.
2021-09-21 16:23:07.767 INFO 15576 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@3700ec9c testClass = MemberServiceIntegrationTest, testInstance = hello.hellospring.service.MemberServiceIntegrationTest@27dc627a, testMethod = 회원가입@MemberServiceIntegrationTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@2002348 testClass = MemberServiceIntegrationTest, locations = '{}', classes = '{class hello.hellospring.HelloSpringApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4d14b6c2, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2657d4dd, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@387a8303, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7eecb5b8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@5dafbe45, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@71623278], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.jdbc.support.JdbcTransactionManager@570ba13]; rollback [true] 2021-09-21 16:23:09.376 INFO 15576 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@3700ec9c testClass = MemberServiceIntegrationTest, testInstance = hello.hellospring.service.MemberServiceIntegrationTest@27dc627a, testMethod = 회원가입@MemberServiceIntegrationTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@2002348 testClass = MemberServiceIntegrationTest, locations = '{}', classes = '{class hello.hellospring.HelloSpringApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4d14b6c2, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2657d4dd, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@387a8303, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7eecb5b8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@5dafbe45, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@71623278], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]] 2021-09-21 16:23:09.428 INFO 15576 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2021-09-21 16:23:09.466 INFO 15576 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
 
어떤 문제일까요?
 
 

MVC spring spring-boot java

답변 4

1

Stanley

o_o0122님, 혹시 JDBCMemberRepository 의 save 메소드에서 conn 변수를 얻어올 때, getConnection()이 아닌 dataSource.getConnection() 을 이용하지 않으셨나요?

정확한 원인은 모르겠지만 아마도 Connection 이 동일하게 유지되는 경우에만 이 코드가 동작하는 것 같습니다. 즉 Transaction Manager 가 관리하는 경우에만 Transactional annotation이 동작하는 것 같습니다. 

0

김영한

안녕하세요. o_o0122님

전체 프로젝트를 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.

구글 드라이브 업로드 방법은 다음을 참고해주세요.

https://bit.ly/3fX6ygx

 

주의: 업로드시 권한 문제 꼭 확인해주세요

추가로 다음 내용도 코멘트 부탁드립니다.

1. 실행 방법을 알려주세요.

2. 어떻게 문제를 확인할 수 있는지 자세한 설명을 남겨주세요.

감사합니다.

 

0

o_o0122

네 말씀해주신대로 되는 것 같습니다.

데이터도 저장됩니다.

 

 참고로 잘 안되서  jdbc template으로 넘어갔는데 jdbc template으로 하면 rollback이 됩니다.

0

OMG

안녕하세요. o_o0122님, 공식 서포터즈 OMG입니다.

 

MemberServiceIntegrationTest 클래스의 어노테이션을 확인해주세요.(@Transactional 누락 여부)

위와 같이 되어있다면

 

테스트에서 추가한 데이터인지 이전 강의에서 웹 상에서 등록한 데이터인지 확인이 필요해 보입니다.

테스트 실행 시 입력한 데이터가 맞을까요?

 

회원 객체 생성을 테스트에서 생성한 것인지 확인하기 위해 구분 가능하도록 값 설정을 하여(name과 age) 테스트를 실행하여 확인해보시겠어요?

 

감사합니다.

0

o_o0122

답변 감사합니다!

당연히 식별해서 테스트 해보았습니다.

 

@SpringBootTest
@Transactional
class MemberServiceIntegrationTest {

@Autowired MemberService memberService;
@Autowired MemberRepository memberRepository;

@Test
void 회원가입() {
//given
Member member = new Member();
member.setName("spring_at_test");

//when
Long saveId = memberService.join(member);

//then
Member findMember = memberService.findOne(saveId).get();
assertThat(member.getName()).isEqualTo(findMember.getName());
}

 

0

OMG

요청사항에 대해 확인해주셔서 감사합니다.

 

하나만 더 여쭤볼게요,

@Rollback(false)를 추가하면 결과가 어떻게 될까요?

데이터 저장 유무와 커밋 메시지가 출력되는지 확인해주시면 감사하겠습니다.

인텔리제이 오류

0

50

1

..

0

113

2

Unused property.....

0

121

2

project JDK is misconfigured

0

165

2

외부 API의 ID 타입(String/UUID)과 내부 도메인의 ID 타입(Long)이 불일치할 때의 설계 정석

0

101

2

단위/통합 테스트 버전충돌 문제

0

103

2

❗️springboot 4.0.2 버전 aspectj dependency 설정❗️

0

256

1

왜 컨트롤러는 변한게 없는데 새로 만든 html 파일이 뜨나요?

0

124

2

윈도우 build test오류 질문

1

123

2

테스트 관련 공부에 대한 조언을 얻고 싶습니다

0

112

2

테스트 실행 시 에러 질문

0

315

1

name을 통한 비교와 객체를 통한 비교

0

82

1

빌드 후 libs 없음

1

149

1

윈도우 gradlew.bat 에러

0

186

1

@PostMapping("/members/new")가 동작하지 않습니다

0

98

1

java static class와 kotlin class

0

89

1

스프링 DB연결

0

145

1

소요 시간

0

96

2

ddl.sql에 빨간 밑줄

1

118

2

welcome page 에러

0

200

3

잘 모르겠습니다.

0

172

2

fail을 똑같이 쳤는데 오류가 발생해요

0

173

2

index.html Welcome page

0

137

1

프로젝트 gradle-groovy ?

0

403

1