해결된 질문
작성
·
622
0
AnnotationConfigApplicationContext
를 사용해 테스트 코드를 수정해봤더니 첨부한 사진과 같이 테스트에 실패하였습니다.package japbook.jpashop.service;
import japbook.jpashop.AutoAppConfig;
import japbook.jpashop.domain.Member;
import japbook.jpashop.repository.MemberRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@Transactional
class MemberServiceTest {
// @Autowired
// MemberService memberService;
//
// @Autowired
// MemberRepository memberRepository;
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class);
MemberService memberService = ac.getBean(MemberService.class);
MemberRepository memberRepository = ac.getBean(MemberRepository.class);
@Test
public void 회원가입() {
// MemberService bean = ac.getBean(MemberService.class);
// System.out.println("bean = " + bean);
Member member = new Member();
member.setName("Cha1");
Long savedMember = memberService.join(member);
Assertions.assertThat(member).isEqualTo(memberRepository.findOne(savedMember));
}
@Test
public void 중복회원예외() {
}
}
package japbook.jpashop;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class AutoAppConfig {
}
답변 4
0
0
안녕하세요. 개발취준생님
이렇게 실행하게 되면 스프링 컨테이너가 총 2개 생성됩니다.
하나는 @SpringBootTest를 통해서 테스트를 수행하면서 스프링 부트가 생성하는 컨테이너가 생성되고,
또 하나는 직접 생성한 스프링 컨테이너입니다.
여기서 테스트에서 수행한 @Transactional를 통해서 트랜잭션이 먼저 수행되고, 그 트랜잭션이 모든 테스트 전체에 영향을 주어야 하는데요.
지금처럼 스프링 컨테이너가 다르면 트랜잭션이 서로 다르게 동작하게 됩니다.
그래서 결과도 기대한 값과 다르게 나오게 됩니다.
감사합니다.
0
https://drive.google.com/file/d/1yZm0825uOExt2y540G6kuO3HNJtjuB1Z/view?usp=sharing
21~25줄의 코드를 이용해 test디렉토리의 service/MemberServiceTest의 회원가입 단위테스트를 실행하면 테스트가 정상적으로 실행되고, 21~25를 주석처리 하고 27~29줄을 이용해 테스트를 실행하면 테스트에 실패합니다.
spring강의를 들을 때 AnnotationConfigApplicationContext를 이용해 bean을 가져와 테스트를 진행하셔서 제가 임의로 @Autowired가 아닌 AnnotationConfigApplicationContext를 이용해 bean을 가져와 진행해봤는데 테스트에 실패했습니다.
AnnotationConfigApplicationContext와 @Autowired의 차이점을 구글링해 찾아봤지만 잘 이해가 가지않아 질문 남깁니다.
2022-08-07 17:30:06.419 INFO 4131 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@5f7b97da testClass = MemberServiceTest, testInstance = japbook.jpashop.service.MemberServiceTest@48463900, testMethod = 회원가입@MemberServiceTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@18b0930f testClass = MemberServiceTest, locations = '{}', classes = '{class japbook.jpashop.JpashopApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@5852c06f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1169afe1, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@13df2a8c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1787f2a0, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@dc9876b, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@11e21d0e], 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.orm.jpa.JpaTransactionManager@6abbdcde]; rollback [true]
2022-08-07 17:30:06.679 DEBUG 4131 --- [ main] org.hibernate.SQL : select member0_.member_id as member_i1_4_, member0_.city as city2_4_, member0_.street as street3_4_, member0_.zipcode as zipcode4_4_, member0_.name as name5_4_ from member member0_ where member0_.name=?
2022-08-07 17:30:06.687 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Cha1]
2022-08-07 17:30:06.695 INFO 4131 --- [ main] p6spy : #1659861006695 | took 6ms | statement | connection 8| url jdbc:h2:mem:bf903789-32b0-4e7c-a39d-964b893862ee
select member0_.member_id as member_i1_4_, member0_.city as city2_4_, member0_.street as street3_4_, member0_.zipcode as zipcode4_4_, member0_.name as name5_4_ from member member0_ where member0_.name=?
select member0_.member_id as member_i1_4_, member0_.city as city2_4_, member0_.street as street3_4_, member0_.zipcode as zipcode4_4_, member0_.name as name5_4_ from member member0_ where member0_.name='Cha1';
2022-08-07 17:30:06.702 DEBUG 4131 --- [ main] org.hibernate.SQL : call next value for hibernate_sequence
2022-08-07 17:30:06.703 INFO 4131 --- [ main] p6spy : #1659861006703 | took 0ms | statement | connection 8| url jdbc:h2:mem:bf903789-32b0-4e7c-a39d-964b893862ee
call next value for hibernate_sequence
call next value for hibernate_sequence;
2022-08-07 17:30:06.758 DEBUG 4131 --- [ main] org.hibernate.SQL : insert into member (city, street, zipcode, name, member_id) values (?, ?, ?, ?, ?)
2022-08-07 17:30:06.759 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [null]
2022-08-07 17:30:06.759 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [null]
2022-08-07 17:30:06.759 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [null]
2022-08-07 17:30:06.759 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [Cha1]
2022-08-07 17:30:06.760 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [BIGINT] - [1]
2022-08-07 17:30:06.761 INFO 4131 --- [ main] p6spy : #1659861006761 | took 0ms | statement | connection 8| url jdbc:h2:mem:bf903789-32b0-4e7c-a39d-964b893862ee
insert into member (city, street, zipcode, name, member_id) values (?, ?, ?, ?, ?)
insert into member (city, street, zipcode, name, member_id) values (NULL, NULL, NULL, 'Cha1', 1);
2022-08-07 17:30:06.765 INFO 4131 --- [ main] p6spy : #1659861006765 | took 0ms | commit | connection 8| url jdbc:h2:mem:bf903789-32b0-4e7c-a39d-964b893862ee
;
2022-08-07 17:30:06.868 DEBUG 4131 --- [ main] org.hibernate.SQL : select member0_.member_id as member_i1_4_0_, member0_.city as city2_4_0_, member0_.street as street3_4_0_, member0_.zipcode as zipcode4_4_0_, member0_.name as name5_4_0_ from member member0_ where member0_.member_id=?
2022-08-07 17:30:06.869 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [1]
2022-08-07 17:30:06.870 INFO 4131 --- [ main] p6spy : #1659861006870 | took 0ms | statement | connection 9| url jdbc:h2:mem:bf903789-32b0-4e7c-a39d-964b893862ee
select member0_.member_id as member_i1_4_0_, member0_.city as city2_4_0_, member0_.street as street3_4_0_, member0_.zipcode as zipcode4_4_0_, member0_.name as name5_4_0_ from member member0_ where member0_.member_id=?
select member0_.member_id as member_i1_4_0_, member0_.city as city2_4_0_, member0_.street as street3_4_0_, member0_.zipcode as zipcode4_4_0_, member0_.name as name5_4_0_ from member member0_ where member0_.member_id=1;
2022-08-07 17:30:06.874 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([city2_4_0_] : [VARCHAR]) - [null]
2022-08-07 17:30:06.874 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([street3_4_0_] : [VARCHAR]) - [null]
2022-08-07 17:30:06.874 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([zipcode4_4_0_] : [VARCHAR]) - [null]
2022-08-07 17:30:06.874 TRACE 4131 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([name5_4_0_] : [VARCHAR]) - [Cha1]
2022-08-07 17:30:06.878 TRACE 4131 --- [ main] org.hibernate.type.CollectionType : Created collection wrapper: [japbook.jpashop.domain.Member.orders#1]
2022-08-07 17:30:06.896 INFO 4131 --- [ main] p6spy : #1659861006896 | took 0ms | rollback | connection 7| url jdbc:h2:mem:test
;
2022-08-07 17:30:06.897 INFO 4131 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@5f7b97da testClass = MemberServiceTest, testInstance = japbook.jpashop.service.MemberServiceTest@48463900, testMethod = 회원가입@MemberServiceTest, testException = org.opentest4j.AssertionFailedError:
expected: japbook.jpashop.domain.Member@1d47b761
but was: japbook.jpashop.domain.Member@7053b64b, mergedContextConfiguration = [WebMergedContextConfiguration@18b0930f testClass = MemberServiceTest, locations = '{}', classes = '{class japbook.jpashop.JpashopApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@5852c06f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1169afe1, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@13df2a8c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1787f2a0, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@dc9876b, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@11e21d0e], 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]]
org.opentest4j.AssertionFailedError:
expected: japbook.jpashop.domain.Member@1d47b761
but was: japbook.jpashop.domain.Member@7053b64b
Expected :japbook.jpashop.domain.Member@1d47b761
Actual :japbook.jpashop.domain.Member@7053b64b
<Click to see difference>
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at japbook.jpashop.service.MemberServiceTest.회원가입(MemberServiceTest.java:41)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
0
안녕하세요. 개발취준생님
전체 프로젝트를 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.
구글 드라이브 업로드 방법은 다음을 참고해주세요.
주의: 업로드시 링크에 있는 권한 문제 꼭 확인해주세요
추가로 다음 내용도 코멘트 부탁드립니다.
1. 실행 방법을 알려주세요.
2. 어떻게 문제를 확인할 수 있는지 자세한 설명을 남겨주세요.
감사합니다.