μ€νλ§ DB μ κ·Ό κΈ°μ
3. μ€νλ§ ν΅ν© ν
μ€νΈ
- μ΄λ² ν
μ€νΈλ μ€νλ§ μ»¨ν
μ΄λμ DBκΉμ§ μ°κ²°ν ν΅ν© ν
μ€νΈμ΄λ€.
- μ΄μ ν
μ€νΈλ μμ μλ° μ½λλ§μΌλ‘ μ΄λ£¨μ΄μ§ λ¨μ ν
μ€νΈμ΄λ€.
- μμν λ¨μ ν
μ€νΈκ° λλΆλΆ μ’μ ν
μ€νΈμ΄κ³ μ€κ³κ° μ λμ΄μλ κ²μ΄λ€.
- @SpringBootTest: μ€νλ§ μ»¨ν
μ΄λμ ν
μ€νΈλ₯Ό ν¨κ» μ€ννλ€.
- @Transactional: ν
μ€νΈ μΌμ΄μ€μ μ΄ μ λ
Έν
μ΄μ
μ΄ μμΌλ©΄, ν
μ€νΈ μμ μ μ νΈλμμ
μ μμνκ³ ν
μ€νΈ μλ£ νμ λ‘€λ°±νλ€. μ΄λ κ² νλ©΄ DBμ λ°μ΄ν°κ° λ¨μ§ μμΌλ―λ‘ λ€μ ν
μ€νΈμ μν₯μ μ£Όμ§ μλλ€. (@AfterEach λΆνμ)
- @Commit: @Transactionalκ° μμ΄λ ν
μ€νΈκ° λλ ν DBμ λ°μνλ€.
package hello.hello.spring.service;
import hello.hello.spring.domain.Member;
import hello.hello.spring.repository.MemberRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
@Transactional
class MemberServiceIntegrationTest {
// μ§μ κ°μ²΄λ₯Ό μμ±νλ λμ (@BeforeEach) μ€νλ§ μ»¨ν
μ΄λλ‘λΆν° λ°μμ¨λ€.(@Autowired)
// μλνλ©΄, ν
μ€νΈ μ½λλ₯Ό μμ±ν λ μ μΌ νΈν λ°©λ²μ μ¬μ©νλ κ²μ΄ μ’λ€.
@Autowired
MemberService memberService;
@Autowired
MemberRepository memberRepository; // μ€νλ§μ λ±λ‘λμ΄ μλ ꡬν체
@Test
@Commit
void νμκ°μ
() {
// given
Member member = new Member();
member.setName("hello123");
// 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("spring123");
Member member2 = new Member();
member2.setName("spring123");
// when
memberService.join(member1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));
Assertions.assertThat(e.getMessage()).isEqualTo("μ΄λ―Έ μ‘΄μ¬νλ νμμ
λλ€.");
}
}