인프런 커뮤니티 질문&답변

윤중진님의 프로필 이미지
윤중진

작성한 질문수

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

회원 기능 테스트

junit5를 이용한 중복_회원_예외 test 실패

해결된 질문

작성

·

1.3K

0

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

윤중진님의 프로필 이미지
윤중진
질문자

그럼 혹시 예외 타입으로 검증하려면 어떤 방식으로 진행해야 하나요?

assertThrows(IllegalStateException.class, () -> {
memberService.join(member2);
});
윤중진님의 프로필 이미지
윤중진
질문자

감사합니다!

0

검증 구문이 잘못되었네요.

테스트 목적에 맞게 작성하려면 다음과 같이 작성하는게 맞을 것 같습니다.

assertThatThrownBy(() -> memberService.join(member2)).hasMessage("a"); 
혹은 hasMessageContaining()로 검증

0

윤중진님의 프로필 이미지
윤중진
질문자

https://drive.google.com/file/d/1ad7-fr6gwuy9a-KvT-KN5n6DjfePyvYN/view?usp=sharing

 

입니다.

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)

 

프로젝트 코드를 살펴봐야 알 것 같습니다.

https://docs.google.com/document/d/1j0jcJ9EoXMGzwAA2H0b9TOvRtpwlxI5Dtn3sRtuXQas/edit#heading=h.yzd7ugcaglvn

를 참고하여 프로젝트 업로드 후 링크를 공유해주세요.

액세스 권한 요청이 출력되지 않도록 크롬의 시크릿창 에서 확인 후 공유 부탁드립니다.

(윈도우 / 맥 : 크롬 시작표시줄 아이콘 우클릭)

0

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

validateDuplicateMember() 메서드에서

throw new IllegalStateException("이미 존재하는 회원입니다.");

isEqualTo(new IllegalStateException("이미 존재하는 회원입니다."));

여기서 두 문자열이 동일해야하는데 다르다고 하는 것으로 보아 다음과 같이 띄어쓰기가 되어 있는지 확인해주세요.

throw new IllegalStateException("이미 존재하는 회원입니다. "); 

해결이 안될 경우 validateDuplicateMember() 코드 화면을 캡쳐해서 올랴주세요.


감사합니다.

문자열 문제인지 아닌지 확인하는 방법으로 "이미 존재하는 회원입니다." 대신 심플한 문자열 "ab" 와 같이 띄어쓰기 없는 문자열로 바꿔서 확인해보시면 될 것 같습니다.

 

윤중진님의 프로필 이미지
윤중진

작성한 질문수

질문하기