테스트도 데이터베이스도 실제 연결하는 종합 테스트 를 진행해보자 !!!
test/java/hello.hellospring/service/MemberServiceTest.java
에 있는 코드를 그대~로 가져와서,
test/java/hello.hellospring/service/MemberServiceIntegrationTest.java
라는 파일을 새로 생성한다!
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
@Transactional
class MemberServiceIntegrationTest {
@Autowired MemberService memberService;
@Autowired MemberRepository memberRepository;
@Test
void 회원가입() {
// 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 중복_회원_예외() {
Member member1 = new Member();
member1.setName("spring");
Member member2 = new Member();
//이름을 member1과 똑같이 설정해줌
member1.setName("spring");
memberService.join(member1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
}
}
@Transactional
: 이 애노테이션이 테스트케이스에 있으면, 테스트 케이스를 실행할 때 트랜잭션을 머저 시작하고, 테스트가 끝나면 다시 롤백을 해줌! DB에 있던 데이터들이 깔끔하게 지워져서 반영이 되지 않는다!
✔️ 전체 실행해보기
좌측 하단 녹색 불이 잘 뜬 것을 확인!
순수 Jdbc
와 동일한 환경설정을 하면 된다.JdbcTemplate
과 MyBatis
같은 라이브러리는 JDBC API
에서 본 반복 코드를 대부분 제거해준다. 하지만 SQL
은 직접 작성해야 한다.✔️ 스프링 JdbcTemplate 회원 리포지토리
main/hello.hellospring/repository/JdbcTemplateMemberRepository.java
생성 후 코드 작성
💡 위와 같이 생성자가 딱 한개만 존재하면
@Autowired
생략 가능!
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class JdbcTemplateMemberRepository implements MemberRepository {
@Autowired // 생략해도 됨
private final JdbcTemplate jdbcTemplate;
public JdbcTemplateMemberRepository(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Member save(Member member) {
SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName("member").usingGeneratedKeyColumns("id");
Map<String, Object> parameters = new HashMap<>();
parameters.put("name", member.getName());
Number key = jdbcInsert.executeAndReturnKey(new
MapSqlParameterSource(parameters));
member.setId(key.longValue());
return member;
}
@Override
public Optional<Member> findById(Long id) {
List<Member> result = jdbcTemplate.query("select * from member where id = ? ", memberRowMapper(), id);
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
return jdbcTemplate.query("select * from member", memberRowMapper());
}
@Override
public Optional<Member> findByName(String name) {
List<Member> result = jdbcTemplate.query("select * from member where name = ? ", memberRowMapper(), name);
return result.stream().findAny();
}
private RowMapper<Member> memberRowMapper() {
return (rs, rowNum) -> {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return member;
};
}
}
✔️ JdbcTemplate을 사용하도록 스프링 설정 변경
main/java/hello.hellospring/SpringConfig.java
의 memberRepository() 수정!
.
.
.
@Bean
public MemberRepository memberRepository() {
// return new MemoryMemberRepository();
// return new JdbcMemberRepository(dataSource);
return new JdbcTemplateMemberRepository(dataSource);
}
.
.
✔️ 실행 확인
test/java/hello.hellospring/service/MemberServiceIntegrationTest.java
을 실행시켜보자 !!
짜라란~👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻
난 녹색 불이 너무 좋아