작성
·
548
0
답변 3
0
이것은 MemoryMemberRepository class 입니다. clearStore() 메서드에서 sequence 초기화 하지 않았을 때 테스트가 깨졌습니다. 따져보면 검증코드 실행 전에 깨진다고 볼 수 있겠네요. 아이디가 초기화 되지 않아서 Member.id == 1L 인 학생이 없으니까요.
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());
}
public void clearStore() {
// sequence = 0L;
store.clear();
}
}
0
테스트 코드입니다.
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;
import static org.assertj.core.api.Assertions.assertThat;
class MemoryMemberRepositoryTest {
MemoryMemberRepository repository = new MemoryMemberRepository();
@AfterEach
public void afterEach() {
repository.clearStore();
}
@Test
void save() {
Member member = new Member();
member.setName("mike");
repository.save(member);
Member saved_member = repository.findById(1L).get();
assertThat(saved_member).isSameAs(member);
}
@Test
void findByName() {
Member member1 = new Member();
member1.setName("dave");
repository.save(member1);
Member member2 = new Member();
member2.setName("camel");
repository.save(member2);
Member saved_member = repository.findByName("dave").get();
assertThat(saved_member).isSameAs(member1);
}
@Test
void findAll() {
Member member1 = new Member();
member1.setName("dave");
repository.save(member1);
Member member2 = new Member();
member2.setName("camel");
repository.save(member2);
List<Member> memberList = repository.findAll();
Assertions.assertThat(memberList.size()).isEqualTo(2);
}
}
Member saved_member = repository.findById(1L).get();
여기서 entity의 id 값 1L로 가져오게 되면 시퀀스에 따라 테스트가 깨집니다.
save된 member의 getId 메서드로 id를 가져와서 검색해야 합니다.
강의 내 작성된 코드를 다시 확인 부탁드립니다.