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

작성자 없음

작성자 정보가 삭제된 글입니다.

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

MemberServiceTest 회원가입 오류

작성

·

267

0

안녕하세요 질문 사항이 있어 글을 남깁니다.

구글링을 통해

Member findMember = memberService.findOne(savId).get();

부분이 오류가 있다는 것을 알았습니다.

그리고 나서 다시 로직을 보면서 다시 하여도 똑같은 오류가 발생해 글을 올립니다.

 

MemberServiceTest 

package com.test.inflearn.service;

import com.test.inflearn.domain.Member;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Optional; //회색

import static org.junit.jupiter.api.Assertions.*; /회색

class MemberServiceTest {

MemberService memberService = new MemberService();


@Test
void 회원가입() {
//given (뭔가가 주어졌을 때)
Member member = new Member();
member.setName("hello");

//when (이걸로 실행 했을 때)
Long savId = memberService.join(member);

//then (결과가 이게 나와야 한다.)
Member findMember = memberService.findOne(savId).get();
Assertions.assertThat(member.getName()).isEqualTo(findMember.getName());
}

@Test
void findMembers() {
}

@Test
void findOne() {
}
}

 

MemberService

package com.test.inflearn.service;

import com.test.inflearn.domain.Member;
import com.test.inflearn.repository.MemberRepository;
import com.test.inflearn.repository.MemoryMemberRepository;
import java.util.List;
import java.util.Optional;

public class MemberService {

private final MemberRepository memberRepository = new MemoryMemberRepository();

/**
* 회원 가입
*/
public Long join(Member member) {
//같은 이름이 있는 중복 가입 X
validateDuplicateMemory(member); //중복 회원 검증
memberRepository.save(member);
return member.getId();

}

private void validateDuplicateMemory(Member member) {
memberRepository.findByName(member.getName())
.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원 입니다.");
});
}


/**
*전체 회원 조회
*/
public List<Member> findMembers() {
return memberRepository.findAll();
}


public Optional<Member> findOne(Long memberId) {
return memberRepository.findById(memberId);
}


}

 

repository = MemberRepository(인터페이스)

package com.test.inflearn.repository;

import com.test.inflearn.domain.Member;

import java.util.List;
import java.util.Optional;

public interface MemberRepository {

Member save(Member member);
Optional<Member> finById(Long id);
Optional<Member> findByName(String name);
List<Member> findAll();

Optional<Member> findById(Long memberId);

// Optional<Member> findById(Long memberId);
}

 

repository = MemberRepository (클래스)

package com.test.inflearn.repository;

import com.test.inflearn.domain.Member;

import java.util.*;

public class MemoryMemberRepository implements MemberRepository {

private Map<Long, Member> store = new HashMap<>();
private static long sequence = 0L;

@Override
public Member save(Member member) {
member.setId(++sequence);
store.put(member.getId(), member);
return member;
}


@Override
public Optional<Member> finById(Long id) {
return Optional.ofNullable(store.get(id));
}


@Override
public Optional<Member> findByName(String name) {
return store.values().stream()
.filter(member -> member.getName().equals(name))
.findAny();
}


@Override
public List<Member> findAll() {
return new ArrayList<>(store.values());
}

@Override
public Optional<Member> findById(Long memberId) {
return Optional.empty();
}


//test 를 한번 할때 마다 지워준다.
public void clearStore() {
store.clear();
}
}

 

domain = Member

package com.test.inflearn.domain;

public class Member {


private Long id;
private String name;


//get, set
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

 

오류 메시지

at java.util.Optional.get(Optional.java:135)

at com.test.inflearn.service.MemberServiceTest.회원가입(MemberServiceTest.java:26)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

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.util.ArrayList.forEach(ArrayList.java:1259)

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.util.ArrayList.forEach(ArrayList.java:1259)

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)

 

 

답변 2

2

안녕하세요. 공상욱님, 공식 서포터즈 David입니다.

memberService의 findOne에서 finById가 아니라 findById 메서드를 호출하고 있습니다.

findById는 무조건 option.empty에 의해 비어있는 Optional을 반환하므로 오류가 발생할 수 밖에 없습니다.

감사합니다.

 

감사합니다!!

0

김영한님의 프로필 이미지
김영한
지식공유자

안녕하세요. 공상욱님

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

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

https://bit.ly/3fX6ygx

 

주의: 업로드시 링크에 있는 권한 문제 꼭 확인해주세요

 

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

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

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

감사합니다.

안녕하세요. 김영한 선생님

다시 새로 만들어 로직을 알아보며, 라이브 코딩을 진행하면서 문제를 해결하습니다.

답변 남겨주셔서 감사합니다.

 

Spring의 두려움이 있었지만 이번 강의를 수강하면서 많은 도움이 되었습니다.

현재 스프링 입문을 모두 수강하였고, 스프링 핵심 원리를 수강 중입니다.

좋은 강의 감사합니다

작성자 없음

작성자 정보가 삭제된 글입니다.

질문하기