* JUnit5λ‘ ν μ€νΈλ₯Ό μ§ννμλ€.
μ’μ ν μ€νΈμ 쑰건
ν μ€νΈλ κ°κ° λ 립μ μΌλ‘ μ€νλμ΄μΌ νλ€. ν μ€νΈ μμμ μμ‘΄κ΄κ³κ° μλ€λ©΄ μ’μ ν μ€νΈκ° μλλ€!
given, when, thenμ μ΄μ©νμ¬ ν μ€νΈ μ½λμ κ°λ μ±μ λμΈλ€.
1. κ°μ λΉκ΅λ‘ κΈ°λ₯μ΄ μ μλμνλμ§ κ²μ¦νκΈ°
assertThat(λΉκ΅λμ).isEqualTo(μ¬μ©μκ° μμνλ κ°)μΌλ‘ νμμ΄ μ μ μ₯λμλμ§ κ²μ¦νλ€.
MemoryMemberRepository.java
@Test
public void save() {
Member member = new Member();
member.setName("spring");
repository.save(member);
Member result = repository.findById(member.getId()).get();
assertThat(member).isEqualTo(result);
}
2. λ©λͺ¨λ¦¬ DB 리μ νκΈ°
Problem
λ€μ λ ν μ€νΈλ κ°κ° μ€ννμ λ λ¬Έμ κ° μμ§λ§ ν μ€νΈ ν΄λμ€ μ 체λ₯Ό μ€ννλ©΄ μ€ν¨κ° λ°μνλ€.
Why
findAll λ©μλμμ spring1, spring2μ΄λ μ΄λ¦μ κ°μ§ νμμ΄ μ΄λ―Έ μμ±λμλλ° μ΄ν findByName λ©μλλ₯Ό μ€ννλ©΄ findAllμμ μ μ₯ν κ°μ²΄κ° λ°νλμ΄ μ€λ₯κ° λ°μνλ€.
Solution
νλμ ν μ€νΈκ° λλλ©΄ repositoryμ μ μ₯λ λ°μ΄ν°λ₯Ό μμ ν΄μ€μΌνλ€.
@AfterEachλ‘ κ° ν μ€νΈ λ©μλ μ€νμ΄ λλ λλ§λ€ repository.clearStore()ν΄μ λ©λͺ¨λ¦¬ DBλ₯Ό 리μ νλ€.
MemoryMemberRepository.java
@AfterEach
public void afterEach() {
repository.clearStore();
}
@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);
}
MemberRepository.java
...
public void clearStore() {
store.clear();
}
3. μμΈ ν μ€νΈνκΈ°
assertThrows(expectedExceptionType, executableClass)λ‘ μμΈλ₯Ό λ°μμν¨ ν
assertThat(e.getMessage()).isEqualTo(msg)λ‘ μμν μ€λ₯λ©μμ§μ λμΌνμ§ κ²μ¦νλ€.
MemberService.java
public Long join(Member member) {
validateDuplicateMember(member); // μ€λ³΅ νμ κ²μ¦
memberRepository.save(member);
return member.getId();
}
private void validateDuplicateMember(Member member) {
memberRepository.findByName(member.getName())
.ifPresent(m -> {
throw new IllegalStateException("μ΄λ―Έ μ‘΄μ¬νλ νμμ
λλ€.");
});
}
MemberServiceTest.java
@Test
public void μ€λ³΅_νμ_μμΈ() {
//given
Member member1 = new Member();
member1.setName("spring");
Member member2 = new Member();
member2.setName("spring");
//when
memberService.join(member1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));
//then
assertThat(e.getMessage()).isEqualTo("μ΄λ―Έ μ‘΄μ¬νλ νμμ
λλ€.");
}
'Spring π±' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[Spring JPA] Entityμ @Setterλ₯Ό μ§μν΄μΌ νλ μ΄μ (0) | 2023.07.27 |
---|---|
[JPA] μμμ± μ»¨ν μ€νΈ (0) | 2023.07.25 |
[Spring] μ±κΈν€ 컨ν μ΄λ (0) | 2023.07.19 |
λΉλ ν¨ν΄(Builder Pattern) (0) | 2023.07.17 |
[Spring] μμ‘΄μ± μ£Όμ (DI)μ΄λ? (0) | 2023.07.13 |