해결된 질문
작성
·
263
2
안녕하세요. MemoryMemberRepositoryTest실행시 오류가 나서 질문드립니다.
MemoryMemberRepositoryTest작동시 save(), findAll()은 정상적으로 작동이 되나 findByName()메서드에서 오류가 납니다.
package com.example.repository;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import com.example.domain.Member;
public class MemoryMemberRepositoryTest {
MemoryMemberRepository repo = new MemoryMemberRepository();
@Test
public void save() {
Member member = new Member();// 선언
member.setName("spring"); //이름 설정
repo.save(member); // 저장
Member result=repo.findById(member.getId()).get();// id로 멤버를 찾음 result로 선언
//optional로 매개변수를 저장해놔서 get()를 사용(권장하지 않음)
//Assertions.assertEquals(member, result);
org.assertj.core.api.Assertions.assertThat(member).isEqualTo(result);
//member가 result와 같은지 확인
//만약 두개가 다르면 다음으로 넘어가지 않음
}
@Test
public void findByName() {
Member member1 = new Member();
member1.setName("spring1");
repo.save(member1);
Member mem2 = new Member();
mem2.setName("spring2");
repo.save(mem2);
Member result= repo.findByName("spring1").get();
org.assertj.core.api.Assertions.assertThat(result).isEqualTo(member1);
}
@Test
public void findAll() {
Member mem1 = new Member();
mem1.setName("spring1");
repo.save(mem1);
Member mem2 = new Member();
mem2.setName("spring2");
repo.save(mem2);
List<Member> result = repo.findAll();
org.assertj.core.api.Assertions.assertThat(result.size()).isEqualTo(2);
}
}
package com.example.repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.example.domain.Member;
public class MemoryMemberRepository implements MemberRepository{
private static 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> findById(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();
//member.getName() 이 name이랑 같은가?
}
@Override
public List<Member> findAll() {
return new ArrayList<>(store.values());
}
}
repository까지 다 확인해보았으나 에러를 찾지 못했습니다.