회원 도메인과 repository & test 만들기
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;
}
}
public interface MemberRepository {
Member save(Member member);
Optional<Member> findById(Long id);
// optional은 java8에서 추가됨.
// findBy가 null값이 반환될 가능성이 있으면 옵셔널을 붙여줌
Optional<Member> findByName(String name);
List<Member> findAll();
}
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(); // 하나라도 찾으면 반환, 없으면 null
}
@Override
public List<Member> findAll() {
return new ArrayList<>(store.values());
}
public void clearStore() {
store.clear();
}
}
public class MemoryMemberRepositoryTest {
MemoryMemberRepository repository = new MemoryMemberRepository();
@AfterEach // 한 메소드가 끝날 때 마다 실행됨
public void afterEach() {
repository.clearStore(); // test가 실행이되고 끝날 때 마다 저장소를 지워줌
}
@Test // 테스트는 서로 순서와 관계없이 설계되어야 함. 공용데이터 또는 저장소를 계속 지워줘야함
public void save() {
//given
Member member = new Member();
member.setName("spring");
//when
repository.save(member);
//then
Member result = repository.findById(member.getId()).get();
// System.out.println("result = " + (result == member));
// Assertions.assertEquals(member, result);
assertThat(member).isEqualTo(result); // 요즘 많이 쓰는 방법
}
@Test
public void findByName() {
//given
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
//when
Member result = repository.findByName("spring1").get();
//then
assertThat(result).isEqualTo(member1);
}
@Test
public void findAll() {
//given
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
//when
List<Member> result = repository.findAll();
//then
assertThat(result.size()).isEqualTo(2);
}
}
이번에 한 건 구현클래스 → 그냥 테스트만 해본 것