package hello.hellospring.domain;
public class Member {
private Long id;
private String name;
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;
}
}
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import java.util.List;
import java.util.Optional;
public interface MemberRepository {
Member save(Member member);
Optional<Member> findById(Long id);
Optional<Member> findByName(String name);
List<Member> findAll();
}
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; // key값 생성
@Override
public Member save(Member member) {
member.setId(++sequence);
store.put(member.getId(), member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
// null인경우 대비+클라이언트에서 뭔가를 할 수 있음
return Optional.ofNullable(store.get(id));
}
@Override
public Optional<Member> findByName(String name) {
// 루프돌면서 확인하다가 동일한게 있으면 반환, 없으면 optional에 null포함시켜 반환
return store.values().stream()
.filter(member -> member.getName().equals(name))
.findAny();
}
@Override
public List<Member> findAll() {
return new ArrayList<>(store.values()); // store.values()=member리스트 값들
}
// 레포지토리 테스트 시 필요
public void clearStore() {
store.clear();
}
}
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.List;
public class MemoryMemberRepositoryTest {
MemoryMemberRepository repository = new MemoryMemberRepository();
@Test
public void save() {
Member member = new Member();
member.setName("gayoung");
repository.save(member);
Member result = repository.findById(member.getId()).get();
// 검증: 내가 입력한 member랑 저장한 후 id로 찾은 result랑 동일?
// System.out.println("result = " + (result == member));
// Assertions.assertEquals(member, result); // 출력되는건 없고 녹색불
Assertions.assertThat(member).isEqualTo(result); // core
}
..
}
@Test
public void findByName() {
Member member1 = new Member();
member1.setName("gayoung1");
repository.save(member1);
Member member2 = new Member();
member2.setName("gayoung2");
repository.save(member2);
Member result = repository.findByName("gayoung1").get(); // .get으로 꺼내기
Assertions.assertThat(result).isEqualTo(member1);
}
@Test
public void findAll() {
Member member1 = new Member();
member1.setName("gayoung1");
repository.save(member1);
Member member2 = new Member();
member2.setName("gayoung2");
repository.save(member2);
List<Member> result = repository.findAll();
Assertions.assertThat(result.size()).isEqualTo(2);
}
@AfterEach
public void afterEach() {
repository.clearStore();
}