shift+F6 rename
ctrl+Alt+Shift+t refactor하기(그 중 Extract Method를 할 것임)
class에 커서 두고 ctrl+shift+t 자동으로 test코드 생성
ctrl+Alt+v asswertThrows를 IllegalStateException e로 바꿀 때 편함
shift+F10 이전 실행 다시
☆ 비즈니스 요구사항 정리
- 데이터 : 회원ID, 이름
- 기능 : 회원 등록, 조회
- 아직 데이터 저장소가 선정되지 않음(가상의 시나리오)
☆ 일반적인 웹 애플리케이션 계층 구조
컨트롤러 : 웹MVC의 컨트롤러 역할
서비스 : 핵심 비즈니스 로직 구현
리포지트리 : 데이터베이스에 접근, 도메인 객체를 DB에 저장, 관리
도메인 : 비즈니스 도메인 객체 ex) 회원, 주문, 쿠폰 등등 주로 데이터베이스에 저장하고 관리
package start.hellospring.repository;
import start.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 start.hellospring.repository;
import start.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(){
store.clear();
}
}
repository코드.
package start.hellospring.repository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import start.hellospring.domain.Member;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class MemoryMemberRepositoryTest {
MemoryMemberRepository repository=new MemoryMemberRepository();
@AfterEach
public void afterEach(){
repository.clearStore();
}
@Test
public void save(){
Member member=new Member();
member.setName("spring");
repository.save(member);
Member result=repository.findById(member.getId()).get();
//Assertions.assertEquals(member, result);
Assertions.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);
Member result=repository.findByName("spring1").get();
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.findAll();
assertThat(result.size()).isEqualTo(2);
}
}
test코드.
각각의 테스트는 독립적이여야 하기 때문에 repository.clearStore() 메소드로 변수 초기화.(매우 중요한 과정)
package start.hellospring.service;
import start.hellospring.domain.Member;
import start.hellospring.repository.MemberRepository;
import start.hellospring.repository.MemoryMemberRepository;
import java.util.List;
import java.util.Optional;
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())
.ifPresent(m->{
throw new IllegalStateException("이미 존재하는 회원입니다");
});
}
// 전체 회원 조회
public List<Member> findMembers(){
return memberRepository.findAll();
}
public Optional<Member> findOne(Long memberId){
return memberRepository.findById(memberId);
}
}
package start.hellospring.service;
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 start.hellospring.domain.Member;
import start.hellospring.repository.MemoryMemberRepository;
import java.util.Optional;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class MemberServiceTest {
MemberService memberService;
MemoryMemberRepository memberRepository;
@BeforeEach
public void beforeEach(){
memberRepository= new MemoryMemberRepository();
memberService= new MemberService(memberRepository);
}
@AfterEach
public void afterEach(){
memberRepository.clearStore();
}
@Test
void 회원가입() {
//given
Member member = new Member();
member.setName("hello");
//when
Long saveId = memberService.join(member);
//then
Member findMember=memberService.findOne(saveId).get();
Assertions.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);
//assertThrows(IllegalStateException.class, ()->memberService.join(member2));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
/* try{
memberService.join(member2);
fail();
} catch(IllegalStateException e){
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
}*/
//then
}
@Test
void findMembers() {
}
@Test
void findOne() {
}
}
@BeforeEach로 MemberService.java와 같은 memberRepository를 쓰도록 함.
반응형
'Framework > Spring Boot' 카테고리의 다른 글
회원 웹 기능 - 홈 화면 추가 (0) | 2020.12.12 |
---|---|
스프링 빈과 의존관계 (0) | 2020.12.12 |
스프링 웹 개발 기초 (0) | 2020.12.05 |
Build (0) | 2020.12.05 |
View 환경설정 (0) | 2020.12.05 |