작성
·
225
0
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
public class MemoryMemberRepositoryTest {
MemberRepository repository = new MemoryMemberRepository();
@Test
public void save() {
Member member = new Member();
member.setName("ianstream");
repository.save(member);
Member result = repository.findById(member.getId()).get();
Assertions.assertEquals(result, member);
assertThat(member).isEqualTo(result);
}
@Test
public void findByName() {
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
// member1 을 찾으면 에러가 나는데 왜일까..?
Member result = repository.findByName("spring2").get();
assertThat(result).isEqualTo(member2);
}
}
위 코드로 테스트 하면 에러가 안납니다. 그런데 아래와 같이 spring1 을 찾으면 에러가 나네요..
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
public class MemoryMemberRepositoryTest {
MemberRepository repository = new MemoryMemberRepository();
@Test
public void save() {
Member member = new Member();
member.setName("ianstream");
repository.save(member);
Member result = repository.findById(member.getId()).get();
Assertions.assertEquals(result, member);
assertThat(member).isEqualTo(result);
}
@Test
public void findByName() {
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
// member1 을 찾으면 에러가 나는데 왜일까..?
Member result = repository.findByName("spring1").get();
assertThat(result).isEqualTo(member1);
}
}
member1 과 비교하도록 수정도 했는데요.. 아래와 같이 나옵니다
무슨 이유일까요..?
답변 3
1
findAll 함수 테스트도 비슷한 현상인데요. 2개의 멤버를 만들었는데 findAll() 로 하면 하나만 나옵니다. 그게 spring2 만 나오네요..
아래에 멤버 레포지토리 구현 클래스 첨부합니다
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import java.util.*;
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();
}
@Override
public List<Member> findAll() {
return new ArrayList<>(store.values());
}
}
0
0