회원 객체
main/java/hello.hellospring/domain/Member
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;
}
}
회원 리포지토리 인터페이스
main/java/hello.hellospring/repository/MemberRepository
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> finaAll();
}
회원 리포지토리 메모리 구현체
main/java/hello.hellospring/repository/MemoryMemberRepository
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import java.util.*;
/**
* 동시성 문제가 고려되어 있지 않음, 실무에서는 ConcurrentHashMap, AtomicLong 사용 고려
*/
public class MemoryMemberRepository implements MemberRepository{
private static Map<Long, Member> store = new HashMap<>(); // id, Member 저장하는 해쉬맵
private static long sequence = 0L; // id
@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)); // Optional로 감싸면 클라이언트에서 처리가능
}
@Override
public Optional<Member> findByName(String name) {
return store.values().stream()
.filter(member -> member.getName().equals(name))
.findAny();
}
@Override
public List<Member> finaAll() {
return new ArrayList<>(store.values());
}
public void clearStore(){
store.clear();
}
}
회원 서비스 개발
main/java/hello.hellospring/service/MemberService
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import java.util.List;
import java.util.Optional;
//아래와 같이 하면 객체간의 종속성이 존재하여, test와 실제 service에서 사용하는 repository가 같지 않게 될 수도 있다.
/*MemberService memberService = new MemoryMemberRepository();
MemoryMemberRepository memberRepository = new MemberService(memberRepository);*/
public class MemberService {
private final MemberRepository memberRepository;
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
/*
* 회원 가입
*/
public Long join(Member member){
// 같은 이름이 있는 중복 회원X
validateDuplicateMember(member); // 중복회원 검증
memberRepository.save(member);
return member.getId();
}
private void validateDuplicateMember(Member member) {
memberRepository.findByName(member.getName()) // 어차피 optional 반환돼서 ifPresent 바로 가능
.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원입니다.");
});
}
/*
* 전체 회원 조회
*/
public List<Member> findMembers(){
return memberRepository.finaAll();
}
public Optional<Member> findOne(Long memberId) {
return memberRepository.findById(memberId);
}
}
이 예제는 assertj를 이용해 테스트했다. 테스트코드 함수 네이밍은 직관적인 한글로 해도된다.
회원 리포지토리 테스트 케이스
test/java/hello.hellospring/repository/MemoryMemberRepositoryTest
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.*;
class MemoryMemberRepositoryTest {
MemoryMemberRepository repository = new MemoryMemberRepository();
@AfterEach // Test가 끝날때마다 실행하는 메소드
public void afterEach(){
repository.clearStore(); // 해쉬맵 clear
}
@Test
public void save(){
Member member = new Member();
member.setName("spring");
repository.save(member);
Member result = repository.findById(member.getId()).get();
// System.out.println("result = " + (result == member));
// Assertions.assertEquals(member, result); // JUnit
assertThat(member).isEqualTo(result); // 옵션+엔터 눌러서 static import하면 줄여짐
}
@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() {
// 이게 먼저 실행돼서 오류뜸, 테스트는 순서에 상관없이 테스트되게 만들어야함 -> 한 테스트가 끝나면 데이터를 클리어 시켜야한다.
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
List<Member> result = repository.finaAll();
assertThat(result.size()).isEqualTo(2);
}
}
@AfterEach
회원 리포지토리 테스트 케이스
test/java/hello.hellospring/service/MemberServiceTest
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemoryMemberRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class MemberServiceTest {
MemberService memberService;
// MemoryMemberRepository memberRepository = new MemoryMemberRepository(); // 메인이랑 테스트랑 다른 객체
MemoryMemberRepository memberRepository;
@BeforeEach
public void beforeEach(){ // Test 실행 전 돌아가는 코드
memberRepository = new MemoryMemberRepository();
memberService = new MemberService(memberRepository);
}
@AfterEach
public void afterEach(){
memberRepository.clearStore();
}
@Test
void 회원가입() { // join
//given 주어진 상황
Member member = new Member();
member.setName("hello");
//when 실행했을 때
Long saveId = memberService.join(member);
//then 결과
Member findMember = memberService.findOne(saveId).get();
assertThat(member.getName()).isEqualTo(findMember.getName());
}
@Test
public void 중복_회원_예외(){
//given
Member member1 = new Member();
member1.setName("spring");
Member member2 = new Member();
member2.setName("spring");
//when
memberService.join(member1);
/* try{
memberService.join(member2);
fail();
}catch(IllegalStateException e){
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
}
*/
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));// try catch 대신
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
//then
}
@Test
void findMembers() {
}
@Test
void findOne() {
}
}
@BeforeEach
참고
스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard