junit5를 이용한 중복_회원_예외 test 실패
junit5를 이용해서 중복회원 테스트를 짜보았습니다.
@Test
public void 중복_회원_예외() throws Exception {
//given
Member member1 = new Member();
member1.setName("kim");
Member member2 = new Member();
member2.setName("kim");
//when
memberService.join(member1);
//then
assertThatThrownBy(() -> memberService.join(member2))
.isEqualTo(new IllegalStateException("이미 존재하는 회원입니다."));
}
그런데
expected: java.lang.IllegalStateException: 이미 존재하는 회원입니다.
at jpabook.jpashop.service.MemberServiceTest.중복_회원_예외(MemberServiceTest.java:49)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...(67 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)
but was: java.lang.IllegalStateException: 이미 존재하는 회원입니다.
at jpabook.jpashop.service.MemberService.validateDuplicateMember(MemberService.java:34)
at jpabook.jpashop.service.MemberService.join(MemberService.java:23)
at jpabook.jpashop.service.MemberService$$FastClassBySpringCGLIB$$560b731b.invoke(<generated>)
...(86 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)
아래와 같은 오류가 생기더군요
expected와 but was 가 같은것 같은데 어디가 문제일까요?
답변 5
0
그럼 혹시 예외 타입으로 검증하려면 어떤 방식으로 진행해야 하나요?
0
검증 구문이 잘못되었네요.
테스트 목적에 맞게 작성하려면 다음과 같이 작성하는게 맞을 것 같습니다.
assertThatThrownBy(() -> memberService.join(member2)).hasMessage("a");
혹은 hasMessageContaining()로 검증
0
아래와 같이 "a" 문자열을 message로 넘겨서 테스트를 진행해 보았지만,
같은 에러 메시지가 출력됩니다.
MemberService.java
private void validateDuplicateMember(Member member) {
List<Member> findMembers = memberRepository.findByName(member.getName());
if(!findMembers.isEmpty()){
throw new IllegalStateException("a");
}
}
MemberServiceTest.java
@Test
public void 중복_회원_예외() throws Exception {
//given
Member member1 = new Member();
member1.setName("kim");
Member member2 = new Member();
member2.setName("kim");
//when
memberService.join(member1);
//then
assertThatThrownBy(() -> memberService.join(member2))
.isEqualTo(new IllegalStateException("a"));
}
에러메시지
2022-05-11 23:47:22.899 INFO 10472 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@6c25e6c4 testClass = MemberServiceTest, testInstance = jpabook.jpashop.service.MemberServiceTest@32d46229, testMethod = 중복_회원_예외@MemberServiceTest, testException = org.opentest4j.AssertionFailedError:
expected: java.lang.IllegalStateException: a
at jpabook.jpashop.service.MemberServiceTest.중복_회원_예외(MemberServiceTest.java:49)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...(67 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)
but was: java.lang.IllegalStateException: a
at jpabook.jpashop.service.MemberService.validateDuplicateMember(MemberService.java:34)
at jpabook.jpashop.service.MemberService.join(MemberService.java:23)
at jpabook.jpashop.service.MemberService$$FastClassBySpringCGLIB$$560b731b.invoke(<generated>)
...(86 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed), mergedContextConfiguration = [WebMergedContextConfiguration@85e6769 testClass = MemberServiceTest, locations = '{}', classes = '{class jpabook.jpashop.JpashopApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@7905a0b8, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3eb91815, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@34b9f960, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4bbf6d0e, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@2205a05d, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@5606c0b], 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: java.lang.IllegalStateException: a
at jpabook.jpashop.service.MemberServiceTest.중복_회원_예외(MemberServiceTest.java:49)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...(67 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)
but was: java.lang.IllegalStateException: a
at jpabook.jpashop.service.MemberService.validateDuplicateMember(MemberService.java:34)
at jpabook.jpashop.service.MemberService.join(MemberService.java:23)
at jpabook.jpashop.service.MemberService$$FastClassBySpringCGLIB$$560b731b.invoke(<generated>)
...(86 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)
<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 jpabook.jpashop.service.MemberServiceTest.중복_회원_예외(MemberServiceTest.java:50)
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$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
0
프로젝트 코드를 살펴봐야 알 것 같습니다.
https://docs.google.com/document/d/1j0jcJ9EoXMGzwAA2H0b9TOvRtpwlxI5Dtn3sRtuXQas/edit#heading=h.yzd7ugcaglvn
를 참고하여 프로젝트 업로드 후 링크를 공유해주세요.
액세스 권한 요청이 출력되지 않도록 크롬의 시크릿창 에서 확인 후 공유 부탁드립니다.
(윈도우 / 맥 : 크롬 시작표시줄 아이콘 우클릭)
0
안녕하세요. 윤중진님, 공식 서포터즈 OMG입니다.
validateDuplicateMember() 메서드에서
throw new IllegalStateException("이미 존재하는 회원입니다.");
와 isEqualTo(new IllegalStateException("이미 존재하는 회원입니다."));
여기서 두 문자열이 동일해야하는데 다르다고 하는 것으로 보아 다음과 같이 띄어쓰기가 되어 있는지 확인해주세요.
throw new IllegalStateException("이미 존재하는 회원입니다. ");
해결이 안될 경우 validateDuplicateMember() 코드 화면을 캡쳐해서 올랴주세요.
감사합니다.
0
문자열 문제인지 아닌지 확인하는 방법으로 "이미 존재하는 회원입니다." 대신 심플한 문자열 "ab" 와 같이 띄어쓰기 없는 문자열로 바꿔서 확인해보시면 될 것 같습니다.
OrderServiceTest 상문주문 테스트 시 update 쿼리 문의
0
27
1
sdk 설정 오류
0
64
2
오탈자 - @Transactional
0
60
1
src/test/resources 테스트 경로 문제
0
55
1
상품 등록후 H2 db 출력 순서 바꿀 수 있나요?
0
70
1
MemberRepositoryTest 실행오류
0
86
1
boot 4.x >>> trasasction rolled back log & p6spy(영한님, 수업 자료 업데이트 해주시면 감사하겠습니다!!)
1
191
2
강의 마지막 QueryDSL 사용 부분 질문있습니다
1
152
2
클라이언트에서 isbn과 author 수정 요청을 한 경우에 대해 질문드립니다.
0
56
1
도메인 모델 패턴 vs 트랜잭션 스크립트 패턴
0
79
1
기본 생성자
0
66
1
h2 DB 연결시 jdbc url 변경 이유가 궁금합니다.
0
106
1
멤버서비스테스트 부분에서 막힙니다.
0
173
4
실무에서도 EntityManager를 이용해서 많이 작업하는 편일까요?
0
123
1
초반에 h2 다운로드 과정 꼭 필요한가요?
0
128
2
자신 필드에도 get으로 접근하는 이유가 있을까요?
0
120
1
24분 27초 연관관계 편의 메서드 위치
0
118
1
단건 주문만 가능하게 한건 의도한 부분이신가요?
0
114
2
빌드 툴, Gradle
0
63
1
h2연결은 된 것 같은데 엔티티 테이블까지 작성 후 확인해보아도 테이블이 안보입니다
0
81
2
Repository에서 EntityManager 주입 방식 차이
0
97
1
롬복과 사용자 정의 setter 메서드
0
77
1
주문 목록 조회 fetch join 질문드립니다
0
90
1
dirty checking 질문드립니다.
0
86
1





