Skip to content

Commit

Permalink
Merge pull request #89 from Kusitms-29th-Meetup-TeamE/feat/86/test
Browse files Browse the repository at this point in the history
Test: 배움나누기 테스트 코드 작성
  • Loading branch information
Jeongho427 authored May 23, 2024
2 parents 129d2c8 + cf29e37 commit 39c3764
Show file tree
Hide file tree
Showing 7 changed files with 168 additions and 86 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

import com.meetup.teame.backend.global.exception.CustomException;
import com.meetup.teame.backend.global.exception.ExceptionContent;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import java.util.Objects;

Expand All @@ -27,4 +30,9 @@ public static boolean isAnonymousUser() {
.map(GrantedAuthority::getAuthority)
.anyMatch(role -> role.equals("ROLE_ANONYMOUS"));
}

public static void setupSecurityContextForTest(Long userId) {
UserAuthentication authentication = new UserAuthentication(userId, null, null);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ public class Experience {
@OneToMany(mappedBy = "experience", cascade = CascadeType.ALL)
private List<DirectChatRoom> directChatRooms;

public static Experience of(MyExperienceReq req, User user) {
public static Experience of(String title, String experienceType, String detail, User user) {
return Experience.builder()
.description(req.getTitle())
.type(ExperienceType.of(req.getExperienceType()))
.detail(req.getDetail())
.description(title)
.type(ExperienceType.of(experienceType))
.detail(detail)
.user(user)
.reviewCount(0L)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
@Builder
public class UserOnboardingRes {

private List<String> personalities = new ArrayList<>();
private List<String> personalities;

public static UserOnboardingRes of(User user) {
List<String> personalityDescriptions = user.getPersonalities().stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
import lombok.*;
import org.hibernate.annotations.Comment;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down Expand Up @@ -52,8 +54,9 @@ public class User {
@Comment("사용자 한마디")
private String oneWord;

@Builder.Default
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Experience> experiences;
private List<Experience> experiences = new ArrayList<>();

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<ActivityLike> activityLikes;
Expand All @@ -68,8 +71,9 @@ public class User {
@OneToMany(mappedBy = "mentee", cascade = CascadeType.ALL)
private List<DirectChatRoom> learnedChatRooms;

@Builder.Default
@OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL)
private List<Review> reviewsAboutMe;
private List<Review> reviewsAboutMe = new ArrayList<>();

@OneToMany(mappedBy = "mentee", cascade = CascadeType.ALL)
private List<Review> reviewsByMe;
Expand All @@ -89,4 +93,15 @@ public void update(UpdateUserReq request) {
this.imageUrl = request.getImageUrl();
this.location = request.getLocation();
}

public static User of(String name, String email, Gender gender, Long age, String location) {
return User.builder()
.name(name)
.email(email)
.gender(gender)
.age(age)
.location(location)
.point(0L)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public class UserService {

public ReadMainRes readMainPage() {
Long userId = 50L;
if(!SecurityContextProvider.isAnonymousUser())
if (!SecurityContextProvider.isAnonymousUser())
userId = SecurityContextProvider.getAuthenticatedUserId();
User user = userRepository.findById(userId)
.orElseThrow(() -> new CustomException(ExceptionContent.NOT_FOUND_USER));
Expand Down Expand Up @@ -165,7 +165,7 @@ public String createExperienceProfile(MyExperienceReq req) {
.orElseThrow(() -> new CustomException(ExceptionContent.NOT_FOUND_USER));

user.setOneWord(req.getIntroduce());
Experience experience = Experience.of(req, user);
Experience experience = Experience.of(req.getTitle(), req.getExperienceType(), req.getDetail(), user);
experienceRepository.save(experience);
return "배움 프로필 생성 성공";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package com.meetup.teame.backend.domain.experience.service;

import com.meetup.teame.backend.domain.auth.jwt.SecurityContextProvider;
import com.meetup.teame.backend.domain.experience.dto.request.ReadExperiencesReq;
import com.meetup.teame.backend.domain.experience.dto.response.MyExperienceProfileRes;
import com.meetup.teame.backend.domain.experience.dto.response.ReadExperienceDetailRes;
import com.meetup.teame.backend.domain.experience.dto.response.ReadExperiencesRes;
import com.meetup.teame.backend.domain.experience.entity.Experience;
import com.meetup.teame.backend.domain.experience.entity.Review;
import com.meetup.teame.backend.domain.experience.repository.ExperienceRepository;
import com.meetup.teame.backend.domain.user.entity.Gender;
import com.meetup.teame.backend.domain.user.entity.User;
import com.meetup.teame.backend.domain.user.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.BDDMockito;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.test.context.support.WithMockUser;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;

@ExtendWith(MockitoExtension.class)
class ExperienceServiceTest {
@Mock
private ExperienceRepository experienceRepository;

@Mock
private UserRepository userRepository;

@InjectMocks
private ExperienceService experienceService;

private static final long testUserId = 100;

@BeforeEach
void setUp() {
SecurityContextProvider.setupSecurityContextForTest(testUserId);
}

@Test
@DisplayName("배움나누기 목록 조회 성공")
void readExperiences() {
//given
ReadExperiencesReq req = new ReadExperiencesReq(0L, "latest", "운동");
User me = User.of(
"김철수",
"test1@test",
Gender.MALE,
18L,
"신대방동"
);
User mento = User.of(
"김멘토",
"test2@test",
Gender.MALE,
18L,
"신대방동"
);
List<Experience> experiences = List.of(
Experience.of(
"축구하실 분!",
"운동",
"배움나누기 상세 내용",
mento
),
Experience.of(
"탁구하실 분!",
"운동",
"배움나누기 상세 내용",
mento
),
Experience.of(
"농구하실 분!",
"운동",
"배움나누기 상세 내용",
me
)
);

given(experienceRepository.countExperiences(req.getCategory(), me))
.willReturn((long) experiences.size());
given(experienceRepository.findExperiencesOrderByLatest(0, 6, req.getCategory(), me))
.willReturn(experiences);
given(userRepository.findById(testUserId))
.willReturn(Optional.of(me));

//when
ReadExperiencesRes result = experienceService.readExperiences(req);

//then
assertThat(result.getExperiences()).hasSize(3);
assertThat(result.getExperiences().get(0).getTitle()).isEqualTo("축구하실 분!");
assertThat(result.getExperiences().get(0).getName()).isEqualTo("김멘토");
}

@Test
@DisplayName("배움나누기 내 프로필 조회 성공")
void readMyExperienceProfile() {
//given
User me = User.of(
"김철수",
"test1@test",
Gender.MALE,
18L,
"신대방동"
);
Experience myExperience = Experience.of(
"축구하실 분!",
"운동",
"배움나누기 상세 내용",
me
);
me.getExperiences().add(myExperience);

given(userRepository.findById(testUserId))
.willReturn(Optional.of(me));

//when
MyExperienceProfileRes result = experienceService.readMyExperienceProfile();

//then
assertThat(result.getExperiences()).hasSize(1);
assertThat(result.getName()).isEqualTo("김철수");
}
}

This file was deleted.

0 comments on commit 39c3764

Please sign in to comment.