테스트 코드
class TeamRepositoryTest extends ExperimentalTest{
@Test
@DisplayName("[CASE-1] 팀만 멤버를 가지고 있을 경우")
void func1(){
// given
Member member = Member.builder().name("Andy").build();
Team team = Team.builder().name("FOXEE").build();
team.add(member);
// when
Team savedTeam = teamRepository.save(team);
// then
assertThat(memberRepository.findById(member.getMemberId())
.orElseThrow(RuntimeException::new)
.getTeam().getName()
).isEqualTo("FOXEE");
}
@Test
@DisplayName("[CASE-2] 멤버만 팀을 가지고 있을 경우")
void func2(){
// given
Team team = Team.builder().name("FOXEE").build();
Member member = Member.builder().name("Andy").team(team).build();
// when
memberRepository.save(member);
// then
assertThat(teamRepository.findById(member.getMemberId())
.orElseThrow(RuntimeException::new)
.getName()
).isEqualTo("FOXEE");
}
@Test
@DisplayName("[CASE-3] 멤버와 팀 둘 다 서로 가지고 있을 경우")
void func3(){
// given
Team team = Team.builder().name("FOXEE").build();
Member member = Member.builder().name("Andy").team(team).build();
team.add(member);
// when
teamRepository.save(team);
// then
assertThat(memberRepository.findById(member.getMemberId())
.orElseThrow(RuntimeException::new)
.getName()
).isEqualTo("Andy");
}
}
엔티티
public class Team {
@Id
@GeneratedValue
private Long teamId;
private String name;
@OneToMany(mappedBy="team", cascade = PERSIST)
private List<Member> members;
public void add(Member member){
member.setTeam(this);
this.members.add(member);
}
@Builder
public Team(Long teamId, String name) {
this.members = new ArrayList<>();
this.teamId = teamId;
this.name = name;
}
}
public class Member {
@Id
@GeneratedValue
private Long memberId;
private String name;
@ManyToOne(cascade = PERSIST)
@JoinColumn(name="teamId")
private Team team;
@Builder
public Member(Long memberId, String name, Team team) {
this.memberId = memberId;
this.name = name;
this.team = team;
}
}